在下面的代码中,我试图替换一个包含以下内容的文件的内容。应该将hellohello world和字符串hellohello替换为hello,并将其写回file.Ho以执行此操作
#!/usr/bin/python
import os
new_file_list=[]
all_files=os.listdir("/tmp")
for ff in all_files:
if ff.endswith(".txt"):
new_file_list.append(ff)
for files in new_file_list:
if files == "a.txt":
print "======================================="
file_name="/tmp/"+str(files)
print file_name
f=open(file_name ,"rw")
while True:
print "======================================="
for line in f.readline():
print line
print "======================================="
f.write(line.replace("hellohello","hello"))
print line
else:
break
for line in f.readline():
print line
f.close()发布于 2012-02-16 16:45:16
完成这类简单任务的最简单方法是从文件中读取所有数据,执行替换,然后将新数据写入文件。
下面是一些示例代码,说明您似乎正在尝试执行的操作:
filename = "/tmp/a.txt"
with open(filename, 'r') as f:
data = f.read()
with open(filename, 'w') as f:
f.write(data.replace("hellohello", "hello"))https://stackoverflow.com/questions/9307836
复制相似问题