這篇文章主要介紹了python讀取和輸出到txt,文中通過示例代碼介紹的非常詳細,
讀取txt的數據和把數據保存到txt中是經常要用到的,下面我就總結一下。
讀txt文件
python常用的讀取文件函數有三種read()、readline()、readlines()

以讀取上述txt為例,我們一起來看一下三者的區別
read() 一次性讀全部內容
read() #一次性讀取文本中全部的內容,以字符串的形式返回結果
|
1
2
3
|
with
open
(
"test.txt"
,
"r"
) as f:
#打開文件
data
=
f.read()
#讀取文件
print
(data)
|

readline() 讀取第一行內容
readline() #只讀取文本第一行的內容,以字符串的形式返回結果
|
1
2
3
|
with
open
(
"test.txt"
,
"r"
) as f:
data
=
f.readline()
print
(data)
|

readlines() 列表
readlines() #讀取文本所有內容,並且以數列的格式返回結果,一般配合for in使用
|
1
2
3
|
with
open
(
"test.txt"
,
"r"
) as f:
data
=
f.readlines()
print
(data)
|

可見readlines會讀到換行符,我們可以用如下方法去除:
|
1
2
3
4
|
with
open
(
"test.txt"
,
"r"
) as f:
for
line
in
f.readlines():
line
=
line.strip(
'\n'
)
#去掉列表中每一個元素的換行符
print
(line)
|

寫txt文件
write
|
1
2
|
with
open
(
"test.txt"
,
"w"
) as f:
f.write(
"這是個測試!"
)
#這句話自帶文件關閉功能,不需要再寫f.close()
|
print到文件中
|
1
2
3
|
data
=
open
(
"D:\data.txt"
,
'w+'
)
print
(
'這是個測試'
,
file
=
data)
data.close()
|
讀寫的模式
讀寫文件的時候有不同的模式,下面來總結一下:

輸出文件其它方法:
(1) 直接重定向,Python a.py >>a.txt
(2)doc = open('out.txt','w') print(data_dict,file=doc) doc.close()
(3)
#coding:utf8
import os
def readFile(filename):
file = os.open(filename,'rb')
data=file.readlines()
file.close()
return data
def writeFile(filename,data):
file= os.open(filename,'wb')
file.write(data)
file.close()
print 'File had been writed Succed!'
if __name__=="__main__":
sourcefile = r'./b.py'
outputfile = r'./target.txt'
writeFile(outputfile,readFile(sourcefile))
print 'end!'
