Python I/O替换lin中的单词

2024-09-30 01:23:51 发布

您现在位置:Python中文网/ 问答频道 /正文

嘿,我用python编写了这段代码,它遍历选定的文本文件并读取它。我的目标是读取文件,然后将文件写入一个新文件,并将单词“winter”替换为空。或者从第二次修订的文件中删除这个词。我有两个txt文件称为odetoseasons和odetoseasons\u审查这两个文件的内容是相同的程序启动前。哪个是

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

/这是名为读写.py当我运行这个程序时,它会保留odetoseans中的内容,但会以某种方式删除odetoseans中的内容_删失.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", "")

Tags: 文件textin程序txt内容lineopen
1条回答
网友
1楼 · 发布于 2024-09-30 01:23:51

实际上你的代码中有两个错误。首先,函数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()

相关问题 更多 >

    热门问题