1

Is there a method of creating a text file without opening a text file in "w" or "a" mode? For instance If I wanted to open a file in "r" mode but the file does not exist then when I catch IOError I want a new file to be created e.g.:

while flag == True:
try:

    # opening src in a+ mode will allow me to read and append to file
    with open("Class {0} data.txt".format(classNo),"r") as src:

        # list containing all data from file, one line is one item in list
        data = src.readlines()

        for ind,line in enumerate(data):

            if surname.lower() and firstName.lower() in line.lower():
                # overwrite the relevant item in data with the updated score
                data[ind] = "{0} {1}\n".format(line.rstrip(),score)
                rewrite = True

            else:
                with open("Class {0} data.txt".format(classNo),"a") as src: 
                    src.write("{0},{1} : {2}{3} ".format(surname, firstName, score,"\n"))


    if rewrite == True:

        # reopen src in write mode and overwrite all the records with the items in data
        with open("Class {} data.txt".format(classNo),"w") as src: 
            src.writelines(data)
    flag = False

except IOError:
    print("New data file created")
    # Here I want a new file to be created and assigned to the variable src so when the
    # while loop iterates for the second time the file should successfully open
joyalrj22
  • 115
  • 4
  • 12
  • http://stackoverflow.com/questions/10978869/safely-create-a-file-if-and-only-if-it-does-not-exist-with-python check this out – Shahriar Dec 13 '14 at 16:20
  • This is actually wrong. But you can do it on linux systems`import os; os.system('touch test.txt')` – Bhargav Rao Dec 13 '14 at 16:21
  • 1
    ahh I guess the solution is to create a file in w mode then close it – joyalrj22 Dec 13 '14 at 16:31
  • possible duplicate of [python open does not create file if it doesn't exist](http://stackoverflow.com/questions/2967194/python-open-does-not-create-file-if-it-doesnt-exist) – nbro Mar 06 '15 at 12:17

4 Answers4

3

At the beginning just check if the file exists and create it if it doesn't:

filename = "Class {0} data.txt"
if not os.path.isfile(filename):
    open(filename, 'w').close()

From this point on you can assume the file exists, this will greatly simplify your code.

elyase
  • 39,479
  • 12
  • 112
  • 119
0

No operating system will allow you to create a file without actually writing to it. You can encapsulate this in a library so that the creation is not visible, but it is impossible to avoid writing to the file system if you really want to modify the file system.

Here is a quick and dirty open replacement which does what you propose.

def open_for_reading_create_if_missing(filename):
    try:
        handle = open(filename, 'r')
    except IOError:
        with open(filename, 'w') as f:
            pass
        handle = open(filename, 'r')
    return handle
tripleee
  • 175,061
  • 34
  • 275
  • 318
0

Better would be to create the file if it doesn't exist, e.g. Something like:

import sys, os
def ensure_file_exists(file_name):
    """ Make sure that I file with the given name exists """
    (the_dir, fname) = os.path.split(file_name)
    if not os.path.exists(the_dir):
         sys.mkdirs(the_dir) # This may give an exception if the directory cannot be made.
    if not os.path.exists(file_name):
         open(file_name, 'w').close()

You could even have a safe_open function that did something similar prior to opening for read and returning the file handle.

Steve Barnes
  • 27,618
  • 6
  • 63
  • 73
0

The sample code provided in the question is not very clear, specially because it invokes multiple variables that are not defined anywhere. But based on it here is my suggestion. You can create a function similar to touch + file open, but which will be platform agnostic.

def touch_open( filename):
    try:
        connect = open( filename, "r")
    except IOError:
        connect = open( filename, "a")
        connect.close()
        connect = open( filename, "r")
    return connect

This function will open the file for you if it exists. If the file doesn't exist it will create a blank file with the same name and the open it. An additional bonus functionality with respect to import os; os.system('touch test.txt') is that it does not create a child process in the shell making it faster.

Since it doesn't use the with open(filename) as src syntax you should either remember to close the connection at the end with connection = touch_open( filename); connection.close() or preferably you could open it in a for loop. Example:

file2open = "test.txt"
for i, row in enumerate( touch_open( file2open)):
    print i, row, # print the line number and content

This option should be preferred to data = src.readlines() followed by enumerate( data), found in your code, because it avoids looping twice through the file.

Diogo
  • 11
  • 2