簡體   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