python - 如何在 Python 中编辑文本文件?

标签 python python-2.7

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()

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

最佳答案

在您的代码中只需替换该行

for line in text:

for line in text.readlines():

请注意,这里我假设您正尝试在文件末尾添加输出。读取整个文件后,文件指针位于文件末尾(即使您以 r+ 模式打开文件)。因此,写操作实际上会写入文件末尾,在当前内容之后。

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

这是另一种方法:

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 - 如何在 Python 中编辑文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27717237/

相关文章:

python - (python matplotlib)如何更改 Lollipop 图中每个 Lollipop 的颜色(ax.stem)

python - 导入结果不一致

python - 如何在 Python 2 中加载 Python 3 Pickled SKlearn 模型

python - 碎片 : Sending information to prior function

python - 使用 BFS 的连接组件标记

python - 虾 4 : 400 ERROR when trying to download a users comments

python - 如何将标准输出重定向到 Tkinter 文本小部件

Python通配符匹配

python - 使用预定义文本进行情感分析

python - 什么是 Gridsearch.cv_results_ ,是否可以解释其中的所有内容,即 mean_test_score 等?