2013-05-13 85 views
0
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 

我想读一次,在时间句子,每个句子我试图访问一个字在同一时间....我能够得到我个人需要的东西,但循环不会不重复......这一次迭代后停止....

回答

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 
2

要回答你的问题,为什么循环不会遍历:

range(0,1) 

只包含元素0,因为the upper bound is not included in the result。同样,

range(0,5) 

当作为列表查看时,将会是[0,1,2,3,4]

@ HennyH的回答证明了迭代文件的正确方法。