Python I / O替换行中的单词

时间:2016-04-16 21:35:01

标签: python io

嘿我在python中编写了这段代码,它遍历所选的文本文件并读取它。我的目标是读取文件,然后将文件写在新文件上,并将“winter”替换为“winter”。或者更确切地说,从第二个修订文件中删除该词。我有两个名为odetoseasons的txt文件和odetoseasons_censored这两个文件的内容在程序启动之前是相同的。

I love winter
I love spring
Summer, Fall and winter again.

/这是名为readwrite.py的python文件当我运行程序时,它将内容保存在odetoseasons中,但不知何故删除了odetoseasons_censored.txt的内容,不知道为什么/

# readwrite.py
# Demonstrates reading from a text file and writing to the other

filename = input("Enter file name (without extension): ")
fil1 = filename+".txt"
fil2 = filename+"_censored.txt"
bad_word = ['winter']

print("\nLooping through the file, line by line.")
in_text_file = open(fil1, "r")
out_text_file = open(fil2,"w")
for line in in_text_file:
    print(line)
    out_text_file.write(line)
in_text_file.close()
out_text_file.close()

out_text_file = open(fil2,"w")
for line in fil2 :
     if "winter" in line:
        out_text_file.write(line)
        line.replace("winter", "")

1 个答案:

答案 0 :(得分:0)

实际上代码中有两个错误。首先,函数a.replace()返回具有替换单词的对象,而不是更改原始对象。其次,您正在尝试阅读已打开的文件' w'模式,这是不可能的。如果你需要同时阅读和写作,你应该使用' r +'模式。

以下是您可以使用的正确代码(以及更紧凑的代码): -

filename = input("Enter file name (without extension): ")
fil1 = filename+".txt"
fil2 = filename+"_censored.txt"
bad_word = ['winter']

print("\nLooping through the file, line by line.")
in_text_file = open(fil1, "r")
out_text_file = open(fil2,"w")
for line in in_text_file:
    print(line)
    line_censored = line.replace("winter","")
    print(line_censored)
    out_text_file.write(line_censored)
in_text_file.close()
out_text_file.close()