Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import tempfile
- import itertools as IT
- import os
- def uniquify(path, sep = ''):
- def name_sequence():
- count = IT.count()
- yield ''
- while True:
- yield '{s}{n:d}'.format(s = sep, n = next(count))
- orig = tempfile._name_sequence
- with tempfile._once_lock:
- tempfile._name_sequence = name_sequence()
- path = os.path.normpath(path)
- dirname, basename = os.path.split(path)
- filename, ext = os.path.splitext(basename)
- fd, filename = tempfile.mkstemp(dir = dirname, prefix = filename, suffix = ext)
- tempfile._name_sequence = orig
- return filename
- print(uniquify('/tmp/file.pdf'))
- import os
- index = ''
- while True:
- try:
- os.makedirs('../hi'+index)
- break
- except WindowsError:
- if index:
- index = '('+str(int(index[1:-1])+1)+')' # Append 1 to number in brackets
- else:
- index = '(1)'
- pass # Go and try create file again
- def iter_incrementing_file_names(path):
- """
- Iterate incrementing file names. Start with path and add " (n)" before the
- extension, where n starts at 1 and increases.
- :param path: Some path
- :return: An iterator.
- """
- yield path
- prefix, ext = os.path.splitext(path)
- for i in itertools.count(start=1, step=1):
- yield prefix + ' ({0})'.format(i) + ext
- def safe_open(path, mode):
- """
- Open path, but if it already exists, add " (n)" before the extension,
- where n is the first number found such that the file does not already
- exist.
- Returns an open file handle. Make sure to close!
- :param path: Some file name.
- :return: Open file handle... be sure to close!
- """
- flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY
- if 'b' in mode and platform.system() == 'Windows':
- flags |= os.O_BINARY
- for filename in iter_incrementing_file_names(path):
- try:
- file_handle = os.open(filename, flags)
- except OSError as e:
- if e.errno == errno.EEXIST:
- pass
- else:
- raise
- else:
- return os.fdopen(file_handle, mode)
- # Example
- with safe_open("some_file.txt", "w") as fh:
- print("Hello", file=fh)
- def increment_filename(fn):
- fn, extension = os.path.splitext(path)
- n = 1
- yield fn + extension
- for n in itertools.count(start=1, step=1)
- yield '%s%d.%s' % (fn, n, extension)
- for filename in increment_filename(original_filename):
- if not os.isfile(filename):
- break
- import os
- file_name = "file_name.txt"
- if os.path.isfile(file_name):
- expand = 1
- while True:
- expand += 1
- new_file_name = file_name.split(".txt")[0] + "(" + str(expand) + ")" + ".txt"
- if os.path.isfile(new_file_name):
- continue
- else:
- file_name = new_file_name
- break
Add Comment
Please, Sign In to add comment