Kareem Hegazy
Kareem Hegazy

Reputation: 25

How to modify the contents of text file?

I have a text file contains the following data

Repetition,4213-RTN-01-8 Counts BER,Microwave,Huawei-RTN-Alarms,Packet Drop,2938,Normal,Regional Operations,,,

and I just need to replace , with ,,

My code is

x=open("D:\Work\Robotics\RTN Sheets\pandas.txt","r+")  #open the file with read/write previlage
x.read().replace(",",",,").write() #read the contents and apply the replace action

Then I couldn't find a proper way to add this modification for the Text file.

Upvotes: 1

Views: 100

Answers (3)

Ali Hallaji
Ali Hallaji

Reputation: 4392

change your code to this:

x = open("text.txt", "r")
a = x.read().replace(",", ",,")
x.close()
x = open("text.txt","w")
x.close()

Upvotes: 0

blhsing
blhsing

Reputation: 107124

You should perform a file seek to reset the file pointer to 0 after you read the file so that the file content can be replaced rather than appended:

with open("D:\Work\Robotics\RTN Sheets\pandas.txt", "r+") as file:
    content = file.read()
    file.seek(0)
    file.write(content.replace(',', ',,'))

Upvotes: 0

Alexander Ivanov
Alexander Ivanov

Reputation: 13

You are trying to call .write() method on the string.

Change your second line to x.write(x.read().replace(",",",,")) and also add x.close() at the end.

Hope this helps!

Upvotes: 1

Related Questions