简体   繁体   中英

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.

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!

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(',', ',,'))

change your code to this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM