# coding=utf-8
# 建立乙個檔案,已經存在則覆蓋掉,w,寫,r:讀,a:新增
f = file('myfile.txt', 'w')
f.write("hello world!")
f.flush()
f.write("hello world2!")
f.close()
# 追加
f = file('myfile.txt', 'a')
f.close()
# 遍歷檔案:
a = file('myfile.txt')
for line in a.readlines():
print line
a.close()
# 檔案替換
import fileinput
# inplace=1 標識把匹配後修改的內容寫到檔案中去
for line in fileinput.input('myfile.txt', inplace=1):
line = line.replace('hello', 'nihao')
print line
# inplace=1 標識把匹配後修改的內容寫到檔案中去
for line in fileinput.input('myfile.txt', backup='.bak'):
line = line.replace('hello', 'nihao')
print line
Python學習筆記之檔案
對檔案的操作有 1.開啟檔案 2.檔案處理 3.檔案關閉 檔案變數名 open 檔名 包含路徑 開啟方式 處理 檔案變數名.close開啟方式 意義若檔案存在 若檔案不存在 r 唯讀 開啟返空指標 w 只寫 開啟刪空 新建開啟 a 追加 開啟新建開啟 rb 唯讀二進位制 開啟返空指標 wb 只寫二進...
Python學習之檔案管理
檔案操作 1.檔案路徑 d 學習 python code test.txt 2.編碼方式 utf 8 gbk 3.操作方式 唯讀 r rb 只寫 追加 讀寫 寫讀 以什麼編碼方式儲存的檔案就用什麼編碼方式開啟 開啟檔案 絕對路徑 f open d 學習 python code test.txt mo...
python學習之檔案操作
在python中,操作檔案和目錄的函式一部分放在os模組中,一部分放在os.path模組中。os.listdir 返回path指定的資料夾包含的檔案或資料夾的名字的列表 os.getcwd 返回當前工作目錄 os.chdir 改變當前工作目錄 os.mkdir 建立資料夾 os.makedirs 遞...