2013-02-19 34 views
-5

請誰能幫助我讀txt文件在python試圖讀取Python中的文件

這裏是我的代碼

flink open(2of12inf.txt, "rU") 

但我得到一個錯誤

+2

*你得到了什麼*錯誤? – 2013-02-19 17:14:50

+0

http://nixcraft.com/coding-general/13455-how-python-read-text-file.html – topcat3 2013-02-19 17:15:25

+1

你試過用open(「yourfilename.txt」,「r」)作爲my_open_file:'? – 2013-02-19 17:15:44

回答

3

你忘了=賦值語句和引號:

flink = open('2of12inf.txt', "rU") 

最好的做法是打開一個文件作爲cont因此,它被自動關閉EXT經理(該):

with open('2of12inf.txt', "rU") as flink: 
    # do something with the open file object 

# flink will be closed automatically. 

flinkfile object,這樣你就可以像使用.read().readline()等方法,從中讀取數據。或者你也可以遍歷所有的對象(迭代),以獲得單個行每次:

with open('2of12inf.txt', "rU") as flink: 
    for line in flink: 
     # do something with each line. 

我會使用一個絕對路徑文件,而不是相對路徑,以避免意外:

with open('/path/to/directory/with/2of12inf.txt', "rU") as flink: 

或者您可以使用os.path library來構建絕對路徑:

import os.path 

filename = os.path.expanduser('~/2of12inf.txt') 

with open(filename, "rU") as flink: 

打開一個名爲在當前用戶的主目錄2of12inf.text文件,例如。

+4

2of12inf應該是一個字符串,而不是文字。 – 2013-02-19 17:16:15

+0

@ITNinja:是的,仍在編輯.. – 2013-02-19 17:17:01

+0

你的意思是我需要定義文件 – 2013-02-19 17:19:14

0

使用下面的例子:

#!/usr/bin/python 
# open file 
f = open ("/etc/passwd","r") 

#Read whole file into data 
data = f.read() 

# Print it 
print data 

# Close the file 
f.close() 
0

你或許應該用引號括起來的文件名(並添加弗林克和開放之間的賦值運算符):

flink = open("2of12inf.txt", "rU") 

我也強烈建議,因爲它忍者說,使用,以構建打開一個文件:

with open("2of12inf.txt", "rU") as flink: 
    # do stuff... 

這會照顧關閉文件,就像使用try-finally塊一樣。

+1

*這將處理從公開聲明中引發的任何異常*否,它不會。如果在'with'行下的代碼集中出現異常,它*將*關閉'flink'文件,但這是不同的。 – 2013-02-19 17:56:57

+0

正確,更正。謝謝! – drekyn 2013-02-19 18:18:27