strip a file from empty lines

Viewed 41

Here's my file

first term    word1_0.1    word2_0.2


second term   another word_0.45    last word_0.89

I want my out put to be like this :

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

Here's what I did :

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()

Which gives me the following result :

   first term
    word1_0.1
    word2_0.2



    second term
    another word_0.45
    last word_0.89

I can't seem to strip my final result of those empty lines, Any idea where i went wrong ?

1 Answers

Strip the lines and work on only non empty lines.

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

output value in csv format

Disclaimer: Check if education.txt has tab (\t) between values.

Related