我有一个包含以下数据的文本文件
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
然后我找不到为文本文件添加此修改的正确方法。
答案 0 :(得分:1)
您正在尝试在字符串上调用.write()方法。
将第二行更改为x.write(x.read().replace(",",",,"))
并在末尾添加x.close()
。
希望这会有所帮助!
答案 1 :(得分:0)
读取文件后,应执行文件搜索以将文件指针重置为0,以便可以替换而不是附加文件内容:
with open("D:\Work\Robotics\RTN Sheets\pandas.txt", "r+") as file:
content = file.read()
file.seek(0)
file.write(content.replace(',', ',,'))
答案 2 :(得分:0)
将代码更改为此:
x = open("text.txt", "r")
a = x.read().replace(",", ",,")
x.close()
x = open("text.txt","w")
x.close()