如何使用Python删除文本文件中包含某个单词的行?

问题描述 投票:0回答:1

我有一个结构如下的文本文件:

word 123 etc.
792 test abc
lorem ipsum word
92 testing
random 84
word 184 lmnop

使用Python,如何删除包含单词

word
的每一行?

python text text-files txt
1个回答
0
投票
# Open the input file for reading and create a new file for writing
with open("input.txt", "r") as input_file, open("output.txt", "w") as output_file:
    # Iterate through each line in the input file
    for line in input_file:
        # Check if the line contains the word "word"
        if "word" not in line:
            # Write the line to the output file if it does not contain "word"
            output_file.write(line)
© www.soinside.com 2019 - 2024. All rights reserved.