【问题标题】:Removing line breaks when writing to txt file写入 txt 文件时删除换行符
【发布时间】:2020-10-06 16:51:53
【问题描述】:

当“用户输入”匹配文档“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)

任何帮助将不胜感激。

【问题讨论】:

    标签: python user-controls match line write


    【解决方案1】:

    看来你正在写找到的行加上接下来的 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)
    

    【讨论】:

    • 谢谢,这很有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多