Reputation:
Hello if i have following code:
n = len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))])
for i in range(0, n):
dat_file = r'C1/C10000' + str(i).zfill(2) + '.dat'
csv_file = r'C1_conv/C10000' + str(i).zfill(2) + '.csv'
in_dat = csv.reader(open(dat_file, 'rb'), delimiter = '\t')
out_csv = csv.writer(open(csv_file, 'wb'))
out_csv.writerows(in_dat)
The problem i have is, that the last file stays opened. I tried to close it with in_dat.close()...., but have read that its not possible because it is a parser.
I have read about the 'with' function, but don't know how to put this in. Could someone show me the proper code, please?
Thanks :D
Upvotes: 0
Views: 45
Reputation: 4490
You need to track opened file in a separate variable, and close it after finishing write operation. A better convention is to use with open(fname)
syntax, which close file for you.
You may consult following code snippet to understand things in better way:
with open(infile, 'w') as datfile, open(outfile, 'w') as csvfile:
do_something()
Upvotes: 2