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

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -