[英]How to modify the contents of text file?
我有一个包含以下数据的文本文件
Repetition,4213-RTN-01-8 Counts BER,Microwave,Huawei-RTN-Alarms,Packet Drop,2938,Normal,Regional Operations,,,
我只是需要更换,
用,,
我的代码是
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
然后我找不到为文本文件添加此修改的正确方法。
您正在尝试在字符串上调用 .write() 方法。
将第二行更改为x.write(x.read().replace(",",",,"))
并在末尾添加x.close()
。
希望这可以帮助!
您应该在读取文件后执行文件查找以将文件指针重置为 0,以便可以替换而不是附加文件内容:
with open("D:\Work\Robotics\RTN Sheets\pandas.txt", "r+") as file:
content = file.read()
file.seek(0)
file.write(content.replace(',', ',,'))
将您的代码更改为:
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.