Python 写入txt文件时删除换行符

Python 写入txt文件时删除换行符,python,user-controls,match,line,write,Python,User Controls,Match,Line,Write,当“用户输入”与文档“Updated_word.doc”中的一个单词匹配时,字符串加上以下两行将写入一个名为word_file.txt的单独txt文件中。我遇到的问题是,当我打开txt文件时,它如下所示: Match Word Line 1 Line 2 我知道这可能是一个简单的解决方案,但我正在努力找出一种方法,将这些行写入一个txt文件而不出现换行。例如: Match Word Line 1 Line 2 下面是执行匹配并写入txt文件的代码部分: def grabWord(): s

当“用户输入”与文档“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)
另一种方法是搜索下两个非空行:

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)
if line.strip():
两条下一行=[]
尝试:
而len(两条下一条线)<2:
当前=下一个(行)
如果当前为.strip():
下两行。追加(当前)
除停止迭代外:
#没有足够的下一行符合您的要求
通过
x=[行]+[下两行]
输出文件写入线(x)

谢谢,这非常有帮助。