如何计算python文件中的空行数
我想使用python打印全部空行。我一直在尝试使用以下方式打印:如何计算python文件中的空行数,python,Python,我想使用python打印全部空行。我一直在尝试使用以下方式打印: f = open('file.txt','r') for line in f: if (line.split()) == 0: 但无法获得适当的输出 我一直想把它打印出来。。它会将值打印为0。。不确定代码出了什么问题 打印“\n空白行是”,(总和(line.isspace()表示fname中的行)) 它的打印方式如下: 空白行为0 文件中有7行。 文件中有46个字符。 文件中有8个字。由于空字符串是一个伪值,您可以使用
f = open('file.txt','r')
for line in f:
if (line.split()) == 0:
但无法获得适当的输出
我一直想把它打印出来。。它会将值打印为0。。不确定代码出了什么问题 打印“\n空白行是”,(总和(line.isspace()表示fname中的行)) 它的打印方式如下: 空白行为0 文件中有7行。 文件中有46个字符。
文件中有8个字。由于空字符串是一个伪值,您可以使用: 上面的代码忽略了只有空格的行 如果您想要完全空行,您可能需要使用此选项:
if line in ['\r\n', '\n']:
...
请使用上下文管理器(
和
语句)打开文件:
with open('file.txt') as f:
print(sum(line.isspace() for line in f))
如果行
没有任何非空白字符,则返回True
(==1),否则返回False
(==0)。因此,sum(f中的行的line.isspace())
返回被视为空的行数
总是返回一个列表。两者
if line.split() == []:
及
会有用的。那真是太快了,我亲眼目睹了它的速度
FILE_NAME = 'file.txt'
empty_line_count = 0
with open(FILE_NAME,'r') as fh:
for line in fh:
# The split method will split the word into list. if the line is
# empty the split will return an empty list. ' == [] ' this will
# check the list is empty or not.
if line.split() == []:
empty_line_count += 1
print('Empty Line Count : ' , empty_line_count)
if not line.split():
FILE_NAME = 'file.txt'
empty_line_count = 0
with open(FILE_NAME,'r') as fh:
for line in fh:
# The split method will split the word into list. if the line is
# empty the split will return an empty list. ' == [] ' this will
# check the list is empty or not.
if line.split() == []:
empty_line_count += 1
print('Empty Line Count : ' , empty_line_count)