2013-05-13 87 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的回答證明了迭代文件的正確方法。