IOError: [Errno 22] invalid mode ('w') or filename

SergeProtector picture SergeProtector · Jan 9, 2015 · Viewed 8.5k times · Source

I am getting this error thrown when trying to make a file. It is being designed to take a created .csv file and put it into a plain text file.

I would like it to create a new file after it has been run with the date and time stamp but I seem to get the Errno 22 when trying to generate the file.

Any ideas?

import csv
import time

f = open(raw_input('Enter file name: '),"r")

saveFile = open ('Bursarcodes_'+time.strftime("%x")+ '_'+time.strftime("%X")+
                 '.txt', 'w+')

csv_f = csv.reader(f)

for row in csv_f:
    saveFile.write( 'insert into bursarcode_lookup(bursarcode, note_id)' +
                    ' values (\'' + row[0] + '\', ' + row[1] + ')\n')

f.close()

saveFile.close()

Answer

Andrew Dunai picture Andrew Dunai · Jan 9, 2015

You cannot have slashes (/) and colons (:, but allowed in Unix) in your file name, but they are exactly what strftime generates in its output.

Python tries to help you, it says:

No such file or directory: 'Bursarcodes_01/09/15_19:59:24.txt'

Replace time.strftime("%x") with this:

time.strftime("%x").replace('/', '.')

...and time.strftime("%X") with this:

time.strftime("%X").replace(':', '_')