Python正課29 檔案修改

2022-01-30 05:41:34 字數 1483 閱讀 7662

張一蛋     山東    179    49    12344234523

李二蛋 河北 163 57 13913453521

王全蛋 山西 153 62 18651433422

with open('a.txt',mode='r+t',encoding='utf-8') as f:

res = f.read(9) # 讀取前9個字元:張一蛋 山

print(res)

f.seek(9,0) # 把指標移到第9個bytes

f.write('《男婦女主任》') # 乙個漢字對應3個bytes,此處共有3*5+2=17個bytes

張一蛋《男婦女主任》9    49    12344234523

李二蛋 河北 163 57 13913453521

王全蛋 山西 153 62 18651433422

優點: 在檔案修改過程中同乙份資料只有乙份

缺點: 會過多地占用記憶體

# 檔案的讀取

with open('c.txt',mode='rt',encoding='utf-8') as f:

res=f.read()

data=res.replace('alex','dsb')

print(data)

# 檔案的寫入

with open('c.txt',mode='wt',encoding='utf-8') as f1:

f1.write('111')

優點: 不會占用過多的記憶體

缺點: 在檔案修改過程中同乙份資料存了兩份

alex is sb

sb is alex

egon is hahahahah

import os		# 匯入os模組

with open('c.txt', mode='rt', encoding='utf-8') as f, \

open('.c.txt.swap', mode='wt', encoding='utf-8') as f1:

for line in f:

f1.write(line.replace('alex', 'dsb')) # 把alex替換為dsb

os.remove('c.txt') # 刪除原檔案

os.rename('.c.txt.swap', 'c.txt') # 把臨時檔案重新命名為原檔案

dsb is sb

sb is dsb

egon is hahahahah

Python 入門 29 資料夾操作

資料夾,又稱目錄。關於目錄操作的函式 物件等主要集中在三個標準庫 os os.path shutil。一 os 模組 基本操作 1 建立新目錄 1 os.mkdir r 路徑 目錄名 建立指定的目錄,無返回值,建立不成功則丟擲異常。為了避免斜槓與反斜槓引起的麻煩,路徑 目錄名 應該用原始字串形式,即...

Python3 5檔案修改操作例項分析

1 檔案修改的兩種方式 1 像vim一樣將檔案載入到記憶體中,修改完之後再寫回原始檔。2 開啟檔案,修改後寫入到乙個新的檔案中。注 這裡操作的txt文字檔案可參考前面一篇 python3.5檔案讀與寫操作 usr bin env python coding utf 8 auth程式設計客棧or zh...

python基礎(13) 檔案

檔案的基本方法 可使用函式open,它位於自動匯入的模組io中。1.open函式將檔名作為唯一必不可少的引數,返回乙個可讀取的檔案物件 open a.py a.py mode r encoding cp936 2.如果要寫入檔案,必須通過指定模式來顯式地指出這一點 3.若不存在該檔案,則會產生如下錯...