python - cant close last opened file -
hello if have following code:
n = len([name name in os.listdir(dir) if os.path.isfile(os.path.join(dir, name))]) 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 have is, last file stays opened. tried close in_dat.close()...., have read not possible because parser.
i have read 'with' function, don't know how put in. show me proper code, please?
thanks :d
you need track opened file in separate variable, , close after finishing write operation. better convention use with open(fname)
syntax, close file you.
you may consult following code snippet understand things in better way:
with open(infile, 'w') datfile, open(outfile, 'w') csvfile: do_something()
Comments
Post a Comment