I have this csv file dl.dropboxusercontent.com/s/tb4yc3lm3gg3j22/out.csv and I am trying to replace the last column with the read method below. In my input.csv i have to replace the last filed with some calculation. I trying as below but somehow i am getting ValueError: I/O operation on a closed file. Can you help me point out the mistake. As i am trying to open input file and write everything including the new value to out.csv file which doesnt exist initially but should be constructed on the fly.
def read():
for file in os.listdir("./"):
if file.endswith('.csv'):
fNameFull = os.path.basename(file)
inputFileName = os.path.splitext(file)[0]
with open(fNameFull, "rb") as infile, open('out.csv', "wb") as outfile:
r = csv.DictReader(infile)
w = csv.DictWriter(outfile, r.fieldnames)
w.writeheader()
for row in r:
if not row["col_last"].strip():
row["col_last"] = "calc_value"
w.writerow(row)
if __name__ == '__main__':
main()
read()
Error:
Traceback (most recent call last):
File "C:\Users\hp\Desktop\final\text\finalmod.py", line 50, in <module>
read()
File "C:\Users\hp\Desktop\final\text\finalmod.py", line 39, in read
w.writeheader()
File "C:\Python27\lib\csv.py", line 137, in writeheader
self.writerow(header)
File "C:\Python27\lib\csv.py", line 148, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
ValueError: I/O operation on closed file