写入txt文件时删除换行符

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

当“用户输入”与文档“ Updated_Word.doc”中的单词匹配时,该字符串加上以下两行将被写入一个单独的txt文件中,该文件称为word_file.txt。我遇到的问题是,当我打开txt文件时,它看起来像这样:

Match Word

Line 1

Line 2

我知道这可能是一个简单的解决方案,但我正在努力寻找一种将这些行写入txt文件而不会出现换行符的方法。示例:

Match Word
Line 1
Line 2

这是执行匹配并写入txt文件的代码部分:

def grabWord():
string = input('Input Word Name:\n')
user_input = re.compile(string)
x = user_input.findall('Updated_Word.doc')
    with open('Updated_Word.doc', mode='r') as infile:
    for line in infile:
        if string in line:
            print('Found Match!')
            with open('Word_file.txt', mode='a') as outfile:
                if line.strip():
                    x = [line, next(infile), next(infile), next(infile), next(infile)]
                    outfile.writelines(x)

任何帮助将不胜感激。

python user-controls match line write
1个回答
0
投票

似乎您正在编写找到的行以及接下来的4行,其中有两个只是换行符。

if line.strip():
    x = [line, next(infile), next(infile), next(infile), next(infile)]

快速而肮脏的解决方法是过滤您的最终结果,删除那些原本为空的行:

if line.strip():
    x = [line, next(infile), next(infile), next(infile), next(infile)]
    x = (list(filter(lambda element: element.strip(), x)))
    outfile.writelines(x)

另一种方法是搜索接下来的两个非空行:

if line.strip():
    two_next_lines = []

    try:
        while len(two_next_lines) < 2:
            current = next(line)

            if current.strip():
                two_next_lines.append(current)
    except StopIteration:
        # there are not enough next lines matching your requirements
        pass


    x = [line] + [two_next_lines]
    outfile.writelines(x)
© www.soinside.com 2019 - 2024. All rights reserved.