在任何一門程式語言中,檔案的操作都是最基本的功能。python在檔案操作方面非常的簡單直接,內建了讀寫檔案的函式,在程式中直接呼叫即可。在讀寫檔案中,會有各種各樣的問題,比如檔案是否存在,是否有許可權,如何捕捉讀寫異常,這些在python中都很簡單。
假設我們在專案目錄中已經有了test.txt檔案:
file = open('test.txt','r')
print(file.read())
file.close()
try:
file = open('test.txt','r')
print(file.read())
except ioerror as ierr:
print('read file error: ' + str(ierr))
finally:
if file:
file.close()
使用try-except-finally可以處理檔案開啟的異常,不過有些麻煩,python可以使用with open()
來自動關閉檔案。
try:
with open('test.txt','r') as file_new:
print(file_new.readline())
except ioerror as ierr:
print("read file error: " + str(ierr))
try:
with open('test1.txt','w') as file_write:
file_write.write('hello world!')
except ioerror as ierr:
print("write file error: " + str(ierr))
如果檔案不存在,系統會建立乙個新的檔案,如果已經存在,會覆蓋當前檔案。
import os
print(os.path.abspath('.'))
new_dir = os.path.join(os.path.abspath('.'),'testdir')
print(new_dir)
os.mkdir(new_dir)
關鍵字:import json
,json.dumps
,json.loads
import json
json_obj = dict(name='bob',hobby="basketball")
s = json.dumps(json_obj)
print(s)
json_str=''
d = json.loads(json_str)
print(d)
python檔案處理比較簡單,json格式處理強大,而且更加的普遍實用。
import os
print('檔案操作 - 異常處理')
try:
file = open('test.txt','r')
print(file.read())
except ioerror as ierr:
print('read file error: ' + str(ierr))
finally:
if file:
file.close()
print('檔案操作 - 使用with')
try:
with open('test.txt','r') as file_new:
print(file_new.readline())
except ioerror as ierr:
print("read file error: " + str(ierr))
print('檔案操作 - 寫入檔案')
try:
with open('test1.txt','w') as file_write:
file_write.write('hello world!')
except ioerror as ierr:
print("write file error: " + str(ierr))
try:
with open('test1.txt','r') as file_write:
print(file_write.readline())
except ioerror as ierr:
print("write file error: " + str(ierr))
print('操作檔案目錄')
print(os.path.abspath('.'))
new_dir = os.path.join(os.path.abspath('.'),'testdir')
print(new_dir)
os.mkdir(new_dir)
print("json格式處理")
import json
json_obj = dict(name='bob',hobby="basketball")
s = json.dumps(json_obj)
print(s)
json_str=''
d = json.loads(json_str)
print(d)
Python學習筆記之檔案操作
如何對檔案操作是python學習過程中的必修課程 二 檔案讀取 三 檔案寫入 四 檔案讀寫模式總結 示例 檔案的開啟與關閉是python基礎語法中一項必修的課程 open close f open filename.txt 此時檔案已經開啟 python預設在main檔案目錄下尋找名為filenam...
Python學習筆記之簡單檔案操作
python檔案操作基礎的bif open close 演示 import os 匯入os模組,這裡是在命令列下用python操作,所以需要os模組的函式來切換工作目錄。你也可以直接在操作的檔案目錄下建立乙個.py檔案 os.getcwd 檢視當前工作目錄 os.chdir headfirstpyt...
Python學習筆記之檔案操作總結
readline 方法,從乙個開啟的檔案讀取一行資料 seek 方法可以用來將檔案 退回 到起始位置 close 方法關閉之前開啟的檔案 split 方法可以將乙個字串分解為乙個字串列表 python中不可改變的常量列表成為元組 tuple 一旦將列表資料賦至乙個元組,就不能再改變。元組是不可改變的...