ASH
ASH

Reputation: 20322

How to open a file, replace some strings, and save updates to the same file?

I am trying to loop through all CSV files in a directory, do a find/replace, and save the results to the same file (same name). It seems like this should be easy, but I seem to be missing something here. Here is the code that I'm working with.

import glob
path = 'C:\\Users\\ryans\\OneDrive\\Desktop\\downloads\\Products\\*.csv'
for fname in glob.glob(path):
    print(str(fname))
    with open(str(fname), "w") as f:
        newText = f.read().replace('|', ',').replace(' ', '')
        f.write(newText)

I came across the link below, and tried the concepts listed there, but nothing has worked so far.

How to open a file for both reading and writing?

Upvotes: 0

Views: 125

Answers (2)

ASH
ASH

Reputation: 20322

Here is the final (working) solution.

import glob
import fileinput
path = 'C:\\Users\\ryans\\OneDrive\\Desktop\\downloads\\Products\\*.csv'
for fname in glob.glob(path):
    #print(str(fname))
    with open(fname, 'r+') as f:
        text = f.read().replace(' ', '')
        f.seek(0)
        f.write(text)
        f.truncate()

Thanks for the tip, agaidis!!

Upvotes: 1

peachykeen
peachykeen

Reputation: 4411

You need to open the file using 'r+' instead of 'w'. See below:

import glob
path = 'C:\\Users\\ryans\\OneDrive\\Desktop\\downloads\\Products\\*.csv'
for fname in glob.glob(path):
    print(str(fname))
    with open(str(fname), "r+") as f:
        newText = f.read().replace('|', ',').replace(' ', '')
        f.write(newText)

Upvotes: 2

Related Questions