2010-08-02 19 views
6

我是一個初學者,幾天前剛剛開始學習Python(耶!)從文件讀

所以我遇到了問題。當我運行,該代碼輸出的一切,但文本(在文件中的txt是單獨的線號0-10)

def output(): 
    xf=open("data.txt", "r") 
    print xf 
    print("opened, printing now") 
    for line in xf: 
     print(xf.read()) 
     print("and\n") 
    xf.close() 
    print("closed, done printing") 

回答

2

這應該打印出每個數字在它自己的路線,就像你想要的,少了很多代碼,更具可讀性。

def output(): 
    f = open('data.txt', 'r').read() 
    print f 
+0

謝謝謝謝 – pjehyun 2010-08-02 18:02:45

6

不要使用line,嘗試:

with open('data.txt') as f: 
    for line in f: 
     print line 
1

當你使用for line in xf:你基本上已經遍歷了該文件,隱式讀取每一行。

所有你需要做的是打印:

for line in xf: 
    print(line) 
0

你在代碼for line in xf:閱讀的文本行到變線,所以你需要證明如打印(線)

我想看看教程像python.org一個

1

您看不到線路輸出的原因是因爲您沒有告訴它輸出線路。在迭代line的值時,打印xf.read()。以下是您重新考慮的功能。還添加了使用with statment塊來完成文件自動關閉文件。

(使用xf.close()是沒有錯的,只是少Python的這個例子。)

def output(): 
    with open("data.txt", "r") as xf: 
     print xf 
     print("opened, printing now") 
     for line in xf: 
      print(line) 
      print("and\n") 
    print("closed, done printing")