首先第一步,開啟檔案,有兩個函式可供選擇:open() 和 file()
①. f =open('file.txt',『w』)
...file.close()
②. f =file('file.json','r')
...file.close() #記得開啟檔案時最後不要忘記關閉!
open() 和 file() 都是python的內建函式,返回乙個檔案物件,具有相同的功能,可以任意替換。使用語法為:
f = open(filename, access_mode='r', buffering=-1)
第1個引數是檔名, 2,3引數有預設值,引數2 決定了是以讀的方式『r』 ?還是寫的方式『w』 ?抑或別的方式開啟檔案。
開啟的方式有:
r —— 讀 ; w —— 寫 ; a —— 追加,從eof開始寫,即在檔案末尾寫
r+ w+ a+ —— 都是以讀寫方式開啟
rb —— 二進位制 讀 ; wb —— 二進位制 寫 ;rb+ wb+ ab+ —— 二進位制讀寫
例子:fp = open('c:\users\mpc\desktop\說明.txt')# 預設以讀的方式開啟
fp = open('test.txt','w')# 寫方式開啟
fp = open('data.json','a')#追加方式開啟
第二步,對檔案進行操作
當得到檔案物件這個控制代碼以後(如例子中的fp),就可對檔案進行操作了。
檔案物件的內建操作方法有:輸入,輸出,檔案內移動,以及雜項操作
1. 輸入
函式: read(),readline(),readlines()
將檔案中的內容讀入到 乙個字串變數/列表中
read() : 讀取整個檔案到字串變數中
例子:fp = open('c:\users\mpc\desktop\說明.txt')
all_file = fp.read()
read()有乙個可選的size引數,預設為-1,表示檔案將會被讀至末尾(eof)
readline():讀取開啟檔案中的一行,然後返回整行包括行結束符到字串變數中
readline()也有乙個可選的引數size,預設-1,表示讀至行結束符停止
readlines() : 讀取整個檔案,返回乙個 字串列表 ,列表中的每個元素都是乙個字串,代表一行
例子:
fp = open('c:\users\mpc\desktop\說明.txt')
lines = fp.readlines()
for line in lines:
...
fp.close()
或者 第2 3 行 簡寫為:for line in fp.readlines():
在python2.3之後由於迭代器和檔案迭代(即檔案物件成為了他們自己的迭代器)的引入,
上例有一種更高效的實現方式:
fp = open('c:\users\mpc\desktop\說明.txt')
for line in fp:
...fp.close()
推薦使用這種方法!
2. 輸出
函式:write() , writelines()
將字串/列表 輸出到檔案中
write() : 將字串輸出到檔案
>>>f= open('test.txt','w')
>>>f.write('helloworld!')
>>>f.close()
>>>f= open('test1.txt','w')
>>>f.write('welcome\nto\n china!')
>>>f.close()
>>>f= open('test1.txt','w')
>>>f.write('welcome\nto\n china!')
>>>f.close()
writelines(): 將字串列表 寫入 檔案,注意行結束符並不會自動被加入,如果需要,必須手動在每行的結尾加入行結束符。
什麼意思呢? 看下例:
>>>s= ['你好','夥計']
>>>f= open('test.txt','w')
>>>f.writelines(s)
>>>f.close()
>>>s= ['你好\n','夥計']
>>>f= open('test.txt','w')
>>>f.writelines(s)
>>>f.close()
>>>f = open(r'i:\python\test.txt','w')
>>>f.write('first line\n')
>>>f.write('second line\n')
>>>f.write('third line\n')
>>>f.close()
>>>lines = list(open(r'i:\python\test.txt'))
>>>lines
['firstline\n', 'second line\n', 'third line\n']
>>>first,second,third = open(r'i:\python\test.txt')
>>>first
'firstline\n'
>>>second
'secondline\n'
>>>third
'thirdline\n'
3. 檔案內移動
函式: seek() tell()
seek() :移動檔案讀取指標到制定的位置
tell(): 返回檔案讀取指標的位置
seek()的三種模式:
(1)f.seek(p,0) 移動當檔案第p個位元組處,絕對位置
(2)f.seek(p,1) 移動到相對於當前位置之後的p個位元組
(3)f.seek(p,2) 移動到相對文章尾之後的p個位元組
Python 讀寫txt檔案
1 讀取 usr bin python coding utf 8 import os str r c users d1 desktop test.txt f open str,r content f.read print content f.close 2 寫入 str c users d1 des...
python檔案txt讀寫
在鍵盤隨便敲了幾個字並建立了乙個文字檔案 1.txt 我們要使用python將其進行讀寫操作 1 檔案讀寫操作 讀檔案1.txt 使用open和read f open 1.txt print f.read f.close 輸出 de鍝堝搱dfafadsfasdfasd fasdfasdfjasdkh...
Python讀寫txt檔案
最近,我在嘗試用python製作乙個簡單的桌面軟體,但其中遇見幾個小問題想給大家分享一下 一般檔案讀寫都是這樣的 讀取 f open test.txt r txt f.read f.close 寫入with open test.txt w as f f.write nothing f.close那,...