Python之檔案讀取和寫入

qq_32154655發表於2017-10-27

Python之檔案管理

1.檔案讀取:

匯入模組:import codecs

開啟檔案例項:

#!/usr/bin/env python
# -*- coding:utf8 -*-
# @Time     : 2017/10/27 9:57
# @Author   : hantong
# @File     : file.py

import codecs
f = codecs.open('1.txt',encoding="utf-8") #建議字符集設定,不設定有時候會出現亂碼
txt1 = f.read()
print(txt1)
f.close()

這樣可以讀取檔案所有內容,如果想要按行讀取,則使用readline和readlines

# readline讀取一行即停止,游標處在檔案末尾,readlines則是逐行讀取所有內容,並且生成一個list

程式碼如下:

f = open('1.txt')
t1 = f.readline()
print(t1)
f.close()

結果只顯示檔案第一行

f = open('1.txt')
t2 = f.readlines()
print(t2)
f.close()
結果如下:

['11111\n', '222\n', 'ggg\n', 'eeerr\n', 'jjjj'] 生成了一個列表

如果要讀取下一行,可以使用next,用法與readline一樣,不在詳說。

2.新建寫入檔案

寫入內容到檔案,使用write

程式碼如下:

import codecs
f = codecs.open('2.txt','w')
f.write('hello world\n')
f.write('hello world one\n')
f.write('hello world two\n')
f.write('hello world three\n')
print(f)
f.close()

這樣就可以新建2.txt檔案,並寫入以上內容,程式碼模式與read一樣

3.with的用法

細心的同學都會發現,上面程式碼每次結尾都會使用f.close()關閉檔案,這樣會比較容易出現忘記寫這行語句的情況,這樣的話檔案其實一直是開啟狀態的,為了避免出現這樣的情況,那麼with就應運而生了。

程式碼如下:

with open('2.txt') as f:
    t2 = f.read()
    print(t2)

這樣就可以操作2.txt這個檔案了.無需再寫f.close()關閉檔案,每次操作之後會自行關閉。


















相關文章