with open(sys.argv[2]) as f:
processlist = f.readlines()
for a in range(0,1):
process = processlist[a]
print process
for b in range(0,3):
process1 = process.split()
print process1[b]
sys.argy [2]文件只有2个句子
Sunday Monday
local owner public
我试图一次读一次句子,在每个句子中我试图一次访问一个单词....我能够得到我个别需要的东西,但循环不会迭代。 ..它在第一次迭代后停止......
答案 0 :(得分:3)
with open(sys.argv[2]) as f:
for line in f: #iterate over each line
#print("-"*10) just for demo
for word in line.rstrip().split(): #remove \n then split by space
print(word)
您的文件将生成
----------
Sunday
Monday
----------
local
owner
public
答案 1 :(得分:2)
回答你的问题为什么循环不迭代:
range(0,1)
仅包含元素0
,因为the upper bound is not included in the result。类似地,
range(0,5)
当作为列表查看时,将[0,1,2,3,4]
。
@ HennyH的回答证明了迭代文件的正确方法。