檔案操作
1 檔案的基本操作
jj = open('路徑',mode='模式',encoding='編碼')
jj.write()#寫入
jj.read()#讀取全部
jj.close()#關閉檔案
2 開啟模式
2.1 r / w / a 唯讀只寫
r是唯讀,w是只寫(先清空檔案),a是只寫(只新增不能讀)
2.2 r+ / w+ / a+ 可讀可寫
r+ (**)常用程度
讀:,預設游標位置0,讀時預設從最開始讀
寫:根據游標的位置從當前游標位置開始進行操作,會覆蓋當前游標後面的值
w+ (**)常用程度
讀:預設游標最後或0,讀取時需要調整游標位置
寫:先清空
a+ (*)常用程度
讀:預設游標位置在最後,讀需要調整游標位置
寫:寫入時不論怎麼調整游標位置,永遠寫到最後
2.3 rb / wb / ab 唯讀只寫(二進位制)
rb是唯讀(以二進位制讀取),wb是只寫(以二進位制寫入),ab是(以二進位制追加)
2.4 r+b / w+b / a+b 可讀可寫(二進位制)
rb+(二進位制) (**)常用程度
讀:,預設游標位置0,讀時預設從最開始讀
寫:根據游標的位置從當前游標位置開始進行操作,會覆蓋當前游標後面的值
wb+(二進位制) (**)常用程度
讀:預設游標最後或0,讀取時需要調整游標位置
寫:先清空
ab+(二進位制) (*)常用程度
讀:預設游標位置在最後,讀需要調整游標位置
寫:寫入時不論怎麼調整游標位置,永遠寫到最後
3 操作
3.1 read() , 全部讀到記憶體
read(1)
1表示乙個字元
obj = open('a.txt',mode='r',encoding='utf-8')
data = obj.read(1) # 1個字元
obj.close()
print(data)
1表示乙個位元組
obj = open('a.txt',mode='rb')
data = obj.read(3) # 1個位元組
obj.close()
3.2 write
write(字串)
obj = open('a.txt',mode='w',encoding='utf-8')
obj.write('中午你')
obj.close()
write(二進位制)
obj = open('a.txt',mode='wb')
# obj.write('中午你'.encode('utf-8'))
v = '中午你'.encode('utf-8')
obj.write(v)
obj.close()
3.3 seek(游標位元組位置)
seek(游標位元組位置),無論模式是否帶b,都是按照位元組進行處理。
obj = open('a.txt',mode='r',encoding='utf-8')
obj.seek(3) # 跳轉到指定位元組位置
data = obj.read()
obj.close()
print(data)
obj = open('a.txt',mode='rb')
obj.seek(3) # 跳轉到指定位元組位置
data = obj.read()
obj.close()
print(data)
3.4 tell(), 獲取游標當前位置
tell(), 獲取游標當前所在的位元組位置
obj = open('a.txt',mode='rb')
# obj.seek(3) # 跳轉到指定位元組位置
obj.read()
data = obj.tell()
print(data)
obj.close()
3.5 flush(重新整理)
flush,強制將記憶體中的資料寫入到硬碟
v = open('a.txt',mode='a',encoding='utf-8')
while true:
val = input('請輸入:')
v.write(val)
v.flush()
v.close()
4 關閉檔案
一般方法
v = open('a.txt',mode='a',encoding='utf-8')
v.close()#需要手動關閉,有時候會忘記,占用記憶體空間
方便方法
with open('a.txt',mode='a',encoding='utf-8') as v:
data = v.read()
# 縮排中的**執行完畢後,自動關閉檔案
5 檔案內容的修改
5.1 普通檔案修改
with open('a.txt',mode='r',encoding='utf-8') as f1:
data = f1.read()
new_data = data.replace('飛灑','666')
with open('a.txt',mode='w',encoding='utf-8') as f1:
data = f1.write(new_data)
5.2 大檔案修改
f1 = open('a.txt',mode='r',encoding='utf-8')
f2 = open('b.txt',mode='w',encoding='utf-8')
for line in f1:
new_line = line.replace('阿斯','死啊')
f2.write(new_line)
f1.close()
f2.close()
with open('a.txt',mode='r',encoding='utf-8') as f1, open('c.txt',mode='w',encoding='utf-8') as f2:
for line in f1:
new_line = line.replace()
f2.write(new_line)
python讀檔案 python 檔案讀寫)
writefile test.txt 先自己寫乙個模組。這是乙個中文文件 第二行第三行 第四行 讀這個檔案有兩種方法 可以是f open test.txt 然後 f.read 這樣就讀取檔案裡的所有東西了。然後?f.close 就樣這個檔案便關閉了。還有就是f.readlines 一行一行的讀,這樣...
python開啟檔案 Python檔案開啟模式
python 內建函式 python 內建函式 python open 函式用於開啟乙個檔案,建立乙個 file 物件,相關的方法才可以呼叫它進行讀寫。寫入檔案時,不會自動加入換行,需要手動在末尾加入,在每個元素後面都換行n,可以用 fo.writelines line n for line in ...
python檔案匯入 python 檔案匯入
基本匯入 import time 呼叫的時候 time.sleep 3 匯入包裡某個方法 from time import sleep 呼叫的時候 sleep 3 區別import time和from time import sleep 兩種方法都可以成功匯入,但不同的匯入方式,呼叫的方式也不同。如...