python檔案的讀寫

來源:互聯網
上載者:User

標籤:obj   with open   inf   內容   close   name   readlines   out   flush   

#檔案的開啟
#file_object = open(file_name,access_mode=‘r‘)
# file_name 相對路徑或絕對路徑 access_mode 參數可不加,那就預設為r



# r為了讀取檔案而開啟檔案。檔案指標在開頭
fh=open(‘E:/gitTest/test/abc.txt‘)
fh.tell()     #檔案對象的tell方法擷取檔案指標的位置
fh.read(2) #讀取前兩個字元 .
fh.read()

fh.seek(3) #從開頭指標移動3個位置後開始讀取

fh.close()

str1 = fh.readline() #讀取一行 包含分行符號

str.readlines() #讀取所有行包含分行符號,返回為列表


# w 檔案存在,內容被清空。檔案不存在,建立一個檔案
f=open(‘tmp‘,‘w‘)
f.write(‘abcde‘) #會先寫入到緩衝區去,此時查看檔案是沒有寫進去的
f.flush() #把緩衝區的內容寫到磁碟上去


#為了在檔案末尾追加內容而開啟檔案
f=open(‘tmp‘,‘a‘)

#在python3下open函數可以通過encoding參數指定編碼方式,而在2中不可以
f = open(‘your_file.txt‘, ‘r‘, encoding=‘utf-8‘)


#with 方式開啟檔案 , 執行結束時,系統自動調用f.close()
with open(‘tmp‘,‘r‘) as f:
fc = f.read()

#支援多個檔案的開啟
with open(inFileName) as ifile, open(outFileName,‘w‘) as ofile:
fc = ifile.read()
ofile.write(fc)

python檔案的讀寫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.