Tzahi Kadosh Tzahi Kadosh - 3 months ago 8
Python Question

How to open all files in directory and save the changes on same file?

I'm trying to write script which loops over all CSV files in a specific directory, reads them, and replaces all substrings

_
with
0
.

My code is:

import csv
f = open ('Tripdata_30_20160806.CSV')
csv_f = csv.reader(f)
for i in csv_f:
for l in i:
if "_" in l:
print l.replace("_", "0")
print l
continue
f.close()


My output is:

2199725502
21997255_2
2199868606
21998686_6
2199726205
21997262_5
1756520101
17565201_1
1756384803
17563848_3


How can I be able to read all files in a given directory without specifying the file name? The CSV file names are dynamic.

Second, how can I be able to save the changes on same file?

Answer

If you just want to replace all underscores in the file don't bother with the CSV module. Simply read the file, replace the underscores, then write the modified text back to the file.

filename = 'C:\\path\\to\\file.csv'

f = open(filename)
txt = f.read()
f.close()

f = open(filename, 'w')
f.write(txt.replace("_", "0"))
f.close()

To enumerate the content of a directory you can use os.listdir():

import os

d = 'C:\\some\\folder'

for f in os.listdir(d):
    filename = os.path.join(d, f)