从文件中删除单词

2024-09-27 23:16:32 发布

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

我正在尝试整理以下文件

Fantasy
Supernatural
Fantasy
UrbanFantasy
Fantasy
EpicFantasy
Fantasy
HighFantasy

我想删除由本身出现的单词fantasy,并将新列表放入另一个文件中 我试过了

def getRidofFantasy():
    file = open("FantasyGenres.txt", "r")
    new_file = open("genres/fantasy", "w")
    for line in file:
        if line != "Fantasy":
            new_file.write(line)
    file.close()
    new_file.close()

这不起作用,我不知道为什么。新文件与旧文件相同。有人能解释一下发生了什么,并给出一个正确解决方案的例子吗


Tags: 文件列表newcloselineopen单词整理
3条回答

试试这个

with open('fantasy.txt') as f, open('generes/fantasy', 'w') as nf:
  lines = [line+'\n' for line in f.read().splitlines() if line != "Fantasy"]
  nf.writelines(lines)

在代码中执行for line in fline变量还包括\n(endline)字符,这就是它不起作用的原因

与@Atin的答案类似,您也可以这样做:

with open('fantasy.txt') as f, open('generes/fantasy', 'w') as nf:
  lines = [line for line in f.readlines() if line.strip() != "Fantasy"]
  nf.writelines(lines)

试试这个


def getRidofFantasy():
    with open("FantasyGenres.txt", "r") as file:
        content = [line.strip('\n') for line in file.readlines()]
        new_list = list(filter(lambda a: a != 'Fantasy', content))

    with open("genres/fantasy.txt", "w") as new_file:
        [new_file.write(f'{line}\n') for line in new_list]
    
getRidofFantasy()

相关问题 更多 >

    热门问题