2017-05-08 45 views
-1

嗨,當我嘗試打印列表,它打印出目錄,而不是win.txt的內容。我試圖列舉txt到一個列表中,然後將它附加到列表中,然後在打印完成後再做其他事情。我究竟做錯了什麼?Python。嘗試打印列表,但其唯一的打印目錄結構

import os 

win_path = os.path.join(home_dir, 'win.txt') 

def roundedStr(num): 
    return str(int(round(num))) 
a=[] # i declares outside the loop for recover later 
for i,line in enumerate(win_path): 
# files are iterable 
    if i==0: 
     t=line.split(' ') 
    else: 
     t=line.split(' ') 
     t[1:6]= map(int,t[1:6]) 

a.append(t) ## a have all the data 
a.pop(0) 
print a 

打印出目錄,如例如c:\workspace\win.txt 不是我想要 我希望它來打印win.txt 的內容這需要T [1:6]爲整數,像,並以相同的方式打印出來。

win.txt包含此

05/06/2017 11 21 31 41 59 21 3 
05/03/2017 17 18 49 59 66 9 2 
04/29/2017 22 23 24 45 62 5 2 
04/26/2017 01 15 18 26 51 26 4 
04/22/2017 21 39 41 48 63 6 3 
04/19/2017 01 19 37 40 52 15 3 
04/15/2017 05 22 26 45 61 13 3 
04/12/2017 08 14 61 63 68 24 2 
04/08/2017 23 36 51 53 60 15 2 
04/05/2017 08 20 46 53 54 13 2 

我只想[1] - [6]

+2

縮進在Python重要 - 請編輯您的代碼,以顯示縮進 – barny

+0

的縮進還是錯了,'return'和'if'應進一步縮進和'a.apend(T)'有額外的空間。 – EndermanAPM

+0

P.S. [python docs](https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files)爲文件讀取提供了很好的示例。 (我假設你正在使用基於你的'打印'調用Pythong2 – EndermanAPM

回答

0

我想你想要的是打開文件win.txt「,並閱讀其內容。使用open函數創建一個文件對象,並使用一個塊來對其進行範圍。看我下面的例子。這將讀取文件,並採取每行的前6個數字。

import os 

win_path = os.path.join(home_dir, 'win.txt') 
a=[] # i declares outside the loop for recover later 
with open(win_path, 'r') as file: 
    for i,line in enumerate(file): 
     line = line.strip() 
     print(line) 
     if i==0: 
      t=line.split(' ') 
     else: 
      t=line.split(' ') 
      t[1:7]= map(int,t[1:7]) 
      t = t[1:7] 
     a.append(t) ## a have all the data 
a.pop(0) 
print (a) 
+0

我沒有得到任何附加到a,它只打印出[] – nerdboy

+0

你能提供'win.txt'的測試數據文件嗎? –

+0

我更新了它與我的文章與win.txt PLZ的幫助。 – nerdboy