因此,为了完成不同的任务,我想从命令文件中获取split()函数返回的列表数。文件command.txt
的条目如下:
ps -a
free
我想出的将其转换为列表并获取列表数量的代码是:
with open('command.txt', 'r') as file:
#for i, v in enumerate(file): #I can get the line counts.
# pass
#print i+1
for line in file:
word = line.split()
print word
print len(word)
此代码的输出为:
['ps',' - a']
2
[ '自由']
1
相反,我希望输出只是2.因为word
有2个列表,['ps',' - a']和['free']。任何人都可以建议我如何修改或提出适当的代码。
答案 0 :(得分:2)
你正试图计算线条。一种没有循环的方法:
with open('command.txt','r') as file:
data = file.readlines()
lines = len(data)
print lines
但是,您必须从除最后一行之外的所有行中删除“\ n”。
答案 1 :(得分:1)
如上面的评论中所述,听起来你只是要求一个行数。由于您已经遍历文件,只需添加一个计数器:
n = 0
with open('command.txt', 'r') as file:
for line in file:
word = line.split()
print word
n += 1
print n