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

I get this error when trying to make a file. It is designed to create the created CSV file and puts it in a text file.

I would like it to create a new file after it starts with a date and time stamp, but I seem to get Errno 22 when I try 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() 
+6
source share
2 answers

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

Python is trying to help you, it says:

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

Replace time.strftime("%x") as follows:

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

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

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

Purified and enhanced version:

 import csv import sys import time def make_output_fname(): # Thanks to @Andrew: return time.strftime("Bursarcodes_%x_%X.txt").replace("/", "-").replace(":", "-") def main(csv_fname=None, outfname=None, *args): if not csv_fname: # first arg not given - prompt for filename csv_fname = raw_input("Enter .csv file name: ") if not outfname: # second arg not given - use serialized filename outfname = make_output_fname() with open(csv_fname) as inf, open(outfname, "w") as outf: incsv = csv.reader(inf) for row in incsv: outf.write( "insert into bursarcode_lookup(bursarcode, note_id) values ('{0}', '{1}')\n" .format(*row) ) if __name__=="__main__": # pass any command-line arguments to main() main(*sys.argv[1:]) 

You can also run it from the command line.

Note that if any data items in your csv file contain non-exclusive single quotes ( ' ), you will receive invalid sql code.

+1
source

Source: https://habr.com/ru/post/980780/


All Articles