繁体   English   中英

写入 txt 文件时删除换行符

[英]Removing line breaks when writing to txt file

当“用户输入”匹配文档“Updated_Word.doc”中的单词时,字符串加上以下两行将写入名为 word_file.txt 的单独 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)

任何帮助,将不胜感激。

似乎您正在编写找到的行加上接下来的 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM