1. 程式人生 > >Python之讀取TXT檔案的三種方法

Python之讀取TXT檔案的三種方法

方法一:

#read txt method one
f = open("./image/abc.txt")
line = f.readline()
while line:
    print line
    line = f.readline()
f.close()


方法二:
#read txt method two
f = open("./image/abc.txt")
for line2 in open("./image/abc.txt"):
    print line2



方法三:

#read txt method three
f2 = open("./image/abc.txt","r")
lines = f2.readlines()
for line3 in lines:
    print line3


1、如果TXT檔案中有兩列,可以設定陣列,然後分別獲取資料

2、上述檔案使用的是相對路徑,當然也可以使用絕對路徑