2017-05-08 132 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