简体   繁体   English

如何修改文本文件的内容?

[英]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.您正在尝试在字符串上调用 .write() 方法。

Change your second line to x.write(x.read().replace(",",",,")) and also add x.close() at the end.将第二行更改为x.write(x.read().replace(",",",,"))并在末尾添加x.close()

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:您应该在读取文件后执行文件查找以将文件指针重置为 0,以便可以替换而不是附加文件内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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