-3

i am currently creating a file on run of my application using the simple method

file = open('myfile.dat', 'w+')

however i have noticed that this is overwritting the file on each run, what i want to do is if it already exsists, create a new file called myfilex.dat where x is the number of previous copies of the file, is there a quick and effective way of doing this ?

Thanks :)

EDIT : I know how to check it already exists using the os.path.exists function, but i am am asking if it does exist how can i apend the number of versions on the end easy if that makes sense sorry if it does not

user1685880
  • 15
  • 1
  • 5
  • 1
    So why not check to see if the file already exists? – Mo H. Mar 12 '15 at 19:58
  • 1
    Edited to hopefully be a bit more clear, i can check the file exists, but am trying to append the number of copies that already exist – user1685880 Mar 12 '15 at 20:00
  • Possible duplicate of [How do I create a incrementing filename in Python?](http://stackoverflow.com/questions/17984809/how-do-i-create-a-incrementing-filename-in-python) – Martin Thoma Apr 02 '17 at 11:12

6 Answers6

4

You could use a timestamp, so that each time you will execute the program it will write to a different file:

import time
file = open('myfile.%d.dat' % time.time(), 'w+')
acondolu
  • 333
  • 1
  • 9
3

You can do two things, either Open with append that is file = open('myfile.dat', 'a') or check if file exists and give user option to overwrite. Python have number of option. You can check this question for enlightment How do I check whether a file exists using Python?

Community
  • 1
  • 1
Stefano Mtangoo
  • 6,017
  • 6
  • 47
  • 93
2

Consider

import os

def build_filename(name, num=0):
    root, ext = os.path.splitext(name)
    return '%s%d%s' % (root, num, ext) if num else name

def find_next_filename(name, max_tries=20):
    if not os.path.exists(name): return name
    else:
        for i in range(max_tries):
            test_name = build_filename(name, i+1)
            if not os.path.exists(test_name): return test_name
        return None

If your filename doesn't exist, it'll return your filename.

If your filename does exist, it'll try rootX.extension where root and extension are determined by os.path.splittext and X is an integer, starting at 1 and ending at max_tries (I had it default to 20, but you could change the default or pass a different argument).

If no file can be found, the function returns None.

Note, there are still race conditions present here (a file is created by another process with a clashing name after your check), but its what you said you wanted.

# When the files doesn't exist
print find_next_filename('myfile.dat')  # myfile.dat

# When the file does exist
print find_next_filename('myfile.dat')  # myfile1.dat

# When the file does exist, as does "1" and "2"
print find_next_filename('myfile.dat')  # myfile3.dat
jedwards
  • 29,432
  • 3
  • 65
  • 92
1

Nothing particularly quick, but effective? Sure! I'm used to a backup system where I do:

filename.ext
filename-1.ext # older
filename-2.ext # older still
filename-3.ext # even older

This is slightly harder than what you want to do. You want filename-N.ext to be the NEWEST file! Let's use glob to see how many files match that name, then make a new one!

from glob import glob
import os.path

num_files = len(glob.glob(os.path.join(root, head, filename + "*", ext)))
# where:
#   root = r"C:\"
#   head = r"users\username\My Documents"
#   filename = "myfile"
#   ext = "dat"

if num_files = 0:
    num_files = "" # handles the case where file doesn't exist AT ALL yet

with open(os.path.join(root, head, filename + str(num_files), ext), 'w+'):
    do_stuff_to_file()
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
1

Here is a few solutions for everyone experiencing a similar problem.

  1. Keep YOUR program from overwiting data:
with open('myfile.txt', 'a') as myfile:
    myfile.write('data')

Note: I believe that a+ (not a) allows for reading and writing, but I'm not 100% sure.

  1. Prevent ALL programs from overwriting your data (by setting it to read-only):
from os import chmod
from stat import S_IREAD

chmod('path_to_file', IREAD)

Note: both of these modules are built-in to Python (at least Python 3.10.4) so no need to use pip. Note 2: Setting it to read-only is not the best idea, as programs can set it back. I would combine this with a hash and/or signature to verify the file has not been tampered with to 'invalidate' the data inside and require the user to re-generate the file (eg, to store any temporary but very important data like decryption keys after generating them before deleting them).

Fighter178
  • 303
  • 2
  • 9
-1

Just check to see if your file already exists then?

name = "myfile"
extension =".dat"
x = 0
fileName = name + extension
while(!os.path.exists(fileName)):
    x = x + 1
    fileName = name + x + extension
file = open(fileName, 'w+')
Mo H.
  • 1,788
  • 1
  • 18
  • 28