空字符串也是有内容的,只是没东西
但为空,是指什么都没有
先判断是否为空
if
not
str:
'空对象“
if
not
len(str.strip())
##空字符串
'空字符串'
如果不考虑是哪一种,可以结合来判断
if
not
str
or
not
len(str.strip()):
'空’
python实现去掉空行# coding = utf-8
def clearBlankLine():
file1 = open('text1.txt', 'r', encoding='utf-8') # 要去掉空行的文件
file2 = open('text2.txt', 'w', encoding='utf-8') # 生成没有空行的文件
try:
for line in file1.readlines():
if line == '\n':
line = line.strip("\n")
file2.write(line)
finally:
file1.close()
file2.close()
if __name__ == '__main__':
clearBlankLine()
Python读取一个文本文件,删除文本文件的空行代码如下:
def delblankline(infile, outfile):""" Delete blanklines of infile """
infp = open(infile, "r")o
utfp = open(outfile, "w")
lines = infp.readlines()
for li in lines:
if li.split():
outfp.writelines(li)
infp.close()
outfp.close()
#调用示例
if
__name__ == "__main__":
delblankline("1.txt","2.txt")
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)