从文件[Python 2.7.10]中删除特定单词文件“object”没有rem属性

2024-06-17 12:19:16 发布

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

我似乎不知道如何从我的文本文件中删除“end”这个词。在

print "Max input for today is 30 links"

file = open("tutorials.txt", 'r+')

counter = + 1

while counter <= 30:
    tutorial = raw_input("Enter Tutorial Link :")
    file.write(str(tutorial) + '\n')

 if tutorial == "end":
    file.remove("end") 
    break

file.close()

当我运行脚本时,我得到以下返回:文件'object'没有属性remove

感谢任何帮助:)


Tags: forinputtodayiscounterlinksopentutorial
1条回答
网友
1楼 · 发布于 2024-06-17 12:19:16

以下函数可用于删除文本文件中的特定字符串,并将返回带更正的输出文件:

inputfile = "tutorial.txt"
outputfile = "fixed_tutorial.txt"

def remove_strings():
    delete_list = ["end"]
    filein = open(inputfile)
    fileout = open(outputfile, "w+")
    for line in filein:
        for word in delete_list:
            line = line.replace(word, "")
        fileout.write(line)
    filein.close()
    fileout.close()

if __name__ == '__main__':
    remove_strings()

当然,输入文件必须与保存此函数信息的文件位于同一目录/文件夹中。在

相关问题 更多 >