016-讀取,寫入檔案方法

回覆文章
cajhbb
系統管理員
文章: 903
註冊時間: 2018年 6月 30日, 02:16

016-讀取,寫入檔案方法

文章 cajhbb »

016-讀取,寫入檔案方法
基本語法
1.開啟-->檔案物件=open(路徑,mode=模式) --> r 讀 w 寫 r+ 讀寫
2.讀取全部文件-->檔案物件.read()
3.一次讀取一行-->
for 變數 in 檔案物件:
依序放入變數中
4.寫入-->檔案物件.write(字串) 換行\n
5.關閉檔案--> 檔案物件.close()
6.最佳讀寫檔案法(能自動.安全關閉檔案)
with open(路徑,mode=模式) as 檔案物件:
讀取/寫入檔案的程式
-------------json格式------------------
1.讀取 json格式-->
import json
=json.load(檔案物件)
2.寫入json格式
import json
json.dump(待寫入的資料,檔案物件)

cajhbb
系統管理員
文章: 903
註冊時間: 2018年 6月 30日, 02:16

一般檔案方法

文章 cajhbb »

一般檔案方法

代碼: 選擇全部

#儲存檔案
file=open("ex01.txt",mode="w",encoding="utf-8")#開啟(中文才要加utf-8)
file.write('使用w模式\n會造成覆蓋上次資料')
file.close() #關檔
2022-07-17_142256.jpg
2022-07-17_142256.jpg (10.82 KiB) 已瀏覽 869 次
最佳方法

代碼: 選擇全部

#最佳方案
with open('ex01.txt',mode='w',encoding='utf-8') as file:
    file.write('使用w模式\n會造成覆蓋上次資料')
讀取ex01.txt

代碼: 選擇全部

#讀取方法
with open('ex01.txt',mode='r',encoding='utf-8') as file:
    data=file.read()
print(data)

cajhbb
系統管理員
文章: 903
註冊時間: 2018年 6月 30日, 02:16

全數讀取與依序讀取

文章 cajhbb »

全數讀取與依序讀取

代碼: 選擇全部

#全部讀出與依序讀出後總和
with open('num1.txt',mode='w',encoding='utf-8') as file:
    file.write('5\n4\n3\n2\n1')
#data為全部讀出,line一行一行讀出並相加
sum=0
with open('num1.txt',mode="r",encoding="utf-8") as file:
   data=file.read()
print(data)
with open('num1.txt',mode="r",encoding="utf-8") as file:
    for line in file:
        sum=sum+int(line) #文字轉數字
print('依序讀出之總和=',sum)        
2022-07-17_145139.jpg
2022-07-17_145139.jpg (6.34 KiB) 已瀏覽 865 次
cajhbb
系統管理員
文章: 903
註冊時間: 2018年 6月 30日, 02:16

使用json模式

文章 cajhbb »

使用json模式讀取
2022-07-17_151056.jpg
2022-07-17_151056.jpg (11.62 KiB) 已瀏覽 863 次

代碼: 選擇全部

#使用json讀/寫
import json
with open("config.json",mode="r") as file:
    data=json.load(file)
print(data)#它是一種字典型號,使用key的方法
print("name:",data["name"])
print("version:",data["version"])
2022-07-17_151543.jpg
2022-07-17_151543.jpg (10.16 KiB) 已瀏覽 860 次
使用json模式寫入

代碼: 選擇全部

#使用json讀/寫
import json
with open("config.json",mode="r") as file:
    data=json.load(file)
print(data)#它是一種字典型號,使用key的方法
print("name:",data["name"])
print("version:",data["version"])
#修改字典內部
data["name"]="New Name"
with open("config.json",mode="w") as file:
    json.dump(data,file)
2022-07-17_152237.jpg
2022-07-17_152237.jpg (14.4 KiB) 已瀏覽 859 次
回覆文章