最好使用两个描述符——一个用于读取,另一个用于写入,以提高可读性和单次写操作。
text_read = open('samiam.py', 'r').read()
words_replacer_dict = {" i " : " I ", "-i-" : "-I-"}
replaced_text = ""
for line in text_read.split("\n"):
for word, new_word in words_replacer_dict.items():
replaced_text += line.replace(word, new_word)
text_read.close()
text_write = open('samiam.py', 'w')
text_write.write(replaced_text)
text_write.close()
你甚至可以按计数器写入内容,如果你关心内存的话。只需在生成器表达式中以读模式打开文件并保留引用计数即可满足写操作。
注意:阅读
此处(非官方链接)以更好地了解字典方法。
然而,如果你更喜欢使用读写操作,请始终使用seek操作找到要替换的行,并在完成文件写入后使用flush。但是,你无法通过seek和flush方法替换文件中已经存在的行。你只能向文件中添加一些内容。(例如)
text = open('samiam.py', 'r+')
count = 1
new_text = ""
for line in text:
new_text += "%d:%s\n" % (count, line)
count += 1
text.seek(0)
text.truncate()
text.write(new_text)
text.seek(0)
for line in text:
print line
text.close()
为了更好地理解为什么不能像你希望的那样读写文件,请查看这里。