
檔案通常用于存儲資料和應用系統的參數。python提供了os、os.path、shutil等子產品處理檔案,其中包括打開檔案、讀寫檔案、複制和删除檔案。
1.檔案的建立
檔案的打開和建立可以使用open()函數。open函數的聲明如下:
open(file, mode='r', buttering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
參數file為要打開的檔案,如果檔案不存在,就會建立一個檔案然後打開
mode是指打開模式打開模式見下表:
參數 | 描述 |
---|---|
r | 隻讀方式打開 |
r+ | 讀寫方式打開 |
w | 寫入方式打開,先删除原有内容,再寫入,如果檔案不存在就建立一個 |
w+ | 讀寫方式打開,先删除原有内容,再寫入,如果檔案不存在就建立一個 |
a | 寫入方式打開,在檔案末尾追加,如果檔案不存在就建立一個 |
a+ | 讀寫方式打開,在檔案末尾追加,如果檔案不存在就建立一個 |
b | 以二進制模式打開,可與r、w、a、+結合使用 |
U | 支援所有的換行符号 |
檔案的處理一般分為以下3個步驟:
- 建立并打開檔案,使用file()函數傳回1個file對象。
- 調用file對象的read()、write()等方法處理檔案。
- 調用close()關閉檔案,釋放file對象占用的資源。
示例代碼:
# 建立檔案context = """hello world"""f = open('helloworld.txt', "w")f.write(context)f.close()
2.檔案的讀取
①按行讀取方式readline()
readline()每次讀取檔案一行,需要使用while True循環讀取檔案,當檔案指針移動到檔案的末尾時,依然使用readlinw()讀取檔案會出錯,進而跳出循環。
示例代碼如下:
f = open("hello.txt")while True: line = f.readline() if line: print line else: breakf.close()
②多行讀取方式readlines()
f = file("hello.txt")lines = f.readline()for line in lines: print(line)f.close()
③一次性讀取方式read()
f = open("hello.txt")context = f.read()print(context)f.clse()
3.檔案的寫入
檔案的寫入有兩個方法,分别是write()和writelines()
writelines()方法可以把清單中存儲的内容寫入檔案。
示範代碼如下:
context = ["hello\n", "world\n"]f = file("hello.txt", "w+")f.writelines(context)f.close()
context = "hello world"f = file("hello.txt", "w+")f.write(context)f.close()
writelines()比write()寫檔案的速度更快,如果需要寫檔案的字元串非常多,可以使用writelines()提高效率,如果僅有少量字元串,可以使用write().
4.檔案的删除
檔案的删除使用remove()方法,删除之前需要先判斷檔案是否存在,如果存在則删除,不存在則不需要額外操作。
示範代碼如下:
import osif os.path.exists("hello.txt"): os.remove("hello.txt")
5.檔案的重命名
os子產品的函數rename()可以對檔案或者目錄進行重命名。
示範代碼如下:
import osos.rename("hello.txt", "world.txt")
6.檔案内容的搜尋
廢話不說,直接上代碼
# 統計檔案中字元串'hello'的個數import ref = file('hello.txt', 'r')count = 0lines = f.readlines()p = re.compile(r'hello')for line in lines: hello = p.findall(line) if hello: count = count + 1print(count)
7.配置檔案的通路
配置檔案的格式一般是
[DB]host=ke.comport=3306username=rootpassword=rootdbname=tianpeng_test[REDIS]host=10.10.10.10port=6479password=password
假設上面的配置檔案名稱是test.ini
讀取配置檔案的代碼如下:
# -*- coding:utf-8 -*-import configparserconfig = configparser.ConfigParser()config.read("test.ini")sections = config.sections()print(sections) # 傳回所有的配置塊 db_host = config['DB']['host'] 擷取配置塊DB中的hostprint(db_host)