簡體   English   中英

從空行中刪除文件

[英]strip a file from empty lines

這是我的文件

first term    word1_0.1    word2_0.2


second term   another word_0.45    last word_0.89

我希望我的輸出是這樣的:

first term
word1_0.1
word2_0.2
second term
another word_0.45
last word_0.89

這是我所做的:

with open("education.txt",encoding="utf-8") as openfile:
    for line in openfile:
        if line.strip():
            for part in line.split("\t"):
                file = open('output.csv','a', encoding='utf-8')
                file.write(("".join(part) + "\n"))
                file.close()

這給了我以下結果:

   first term
    word1_0.1
    word2_0.2



    second term
    another word_0.45
    last word_0.89

我似乎無法去除那些空行的最終結果,知道我哪里出錯了嗎?

剝離線條並僅處理非空行。

education.txt

first term  word1_0.1   word2_0.2


second term another word_0.45   last word_0.89

updated_code.py

with open("education.txt",encoding="utf-8") as openfile:
    for line in openfile:
        if line.strip()!="":
            for part in line.strip().split("\t"):
                file = open('output.csv','a', encoding='utf-8')
                file.write(("".join(part) + "\n"))
                file.close()

output.csv

first term
word1_0.1
word2_0.2
second term
another word_0.45
last word_0.89

csv格式的輸出值

免責聲明:檢查education.txt值之間是否有制表符( \t )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM