如何在 Python 中编辑文本文件? [英] How do I edit a text file in Python?

查看:64
本文介绍了如何在 Python 中编辑文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

text = open('samiam.txt', 'r+')
keyword = " i "
keyword2 = "-i-"
replacement = " I "
replacement2 = "-I-"

for line in text:    
    if keyword in line:
        text.write(line.replace(keyword, replacement))
        print line
    elif keyword2 in line:
        text.write(line.replace(keyword2, replacement2))
        print line
    else:
        print line
text.close()

我不完全确定为什么没有将文本写入文件.帮助?

I'm not entirely sure why the text is not being written to the file. help?

推荐答案

在你的代码中只替换一行

In your code just replace the line

for line in text:

for line in text.readlines():

请注意,这里我假设您尝试在文件末尾添加输出.一旦你读完整个文件,文件指针就在文件的末尾(即使你在 r+ 模式下打开文件).因此,写操作实际上会写入文件的末尾,在当前内容之后.

Note that here I am assuming that the you are trying to add the output at the end of the file. Once you have read the entire file, the file pointer is at the end of the file (even if you opened the file in r+ mode). Thus doing a write will actually write to the end of the file, after the current contents.

您可以通过在不同行嵌入 text.tell() 来检查文件指针.

You can examine the file pointer by embedding text.tell() at different lines.

这是另一种方法:

with open("file","r") as file: 
    text=file.readlines() 
i=0 
while i < len(text): 
    if keyword in text[i]: 
        text[i]=text[i].replace(keywork,replacement) 
with open("file","w") as file: 
    file.writelines(text)

这篇关于如何在 Python 中编辑文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆