Python 从空行中删除文件
这是我的档案Python 从空行中删除文件,python,python-3.x,Python,Python 3.x,这是我的档案 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
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
更新的\u 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
免责声明:检查
education.txt
的值之间是否有tab(\t
)。您是否已经在if line.strip():
?@usr2564301之后立即检查了Python认为行中有什么内容,像这样:第一学期单词1\u 0.1单词2\u 0.2第二学期另一个单词0.45最后一个单词0.89