2014-10-07 35 views
-6

所以我下面有這個代碼。基本上,它應該讀取testcase.txt中的行並將它們打印出來,但是當我運行該程序時它會變成空白。任何解決方案?有人可以解釋爲什麼Python不讀這個文件嗎?

testFile = 'testcase.txt' 
file = open(testFile, 'r') 
index = 0 
for line in file: 
    test_list.insert(index,line) 
    index += 1 
file.close() 
+3

此代碼是否運行?你有沒有實例化'''test_list'''? – wnnmaw 2014-10-07 13:44:24

+5

我在代碼中看不到打印語句,所以不確定爲什麼你期望打印任何東西? – 2014-10-07 13:44:28

+0

不是你的問題,但使用'enumerate()'而不是手動計數索引。 – geoffspear 2014-10-07 13:46:27

回答

1

你可能想讀多一點關於蟒蛇file objects'方法的文件,但在這裏:

filecontents = open('testcase.txt').readlines() 
#readlines automatically splits the file up by linebreaks 

for index,line in enumerate(filecontents): 
    print(index,line) 
相關問題