python資料檔案讀寫

2021-09-14 08:44:36 字數 2305 閱讀 3540

comma-separated values 有時也稱為字元分隔值,因為分隔字元也可以不是逗號。以,分隔的檔案叫csv,以\t分隔的叫tsv

import csv 

data=

with

open

(r'data.csv',)

as csvfile:

file_list = csv.reader(csvfile,

'mydialect'

)for line in file_list:

print

(data)

如果檔案是其他分隔符,如\n,則需要傳入分隔符型別。

import csv 

data=

with

open

(r'data.csv',)

as csvfile:

file_list = csv.reader(csvfile,delimiter=

'\t'

)for line in file_list:

print

(data)

列表方式讀取
import csv

with open('data.csv','r',encoding='utf-8') as csvfile:

reader = csv.reader(csvfile)

for row in reader:

# 讀取出的內容是列**式的

print(row,type(row),row[1])

字典方式讀取
import csv

with open('data.csv','r',encoding='utf-8') as csvfile:

reader = csv.dictreader(csvfile)

for row in reader:

# 讀取的內容是字典格式的

print(row['last_name'])

列表方式寫入
import csv

with open('data.csv','a+',encoding='utf-8',newline='') as csvfile:

writer = csv.writer(csvfile)

# 寫入一行

writer.writerow(['1','2','3','4','5','5','6'])

# 寫入多行

writer.writerows([[0, 1, 3], [1, 2, 3], [2, 3, 4]])

字典方式寫入
import csv

with open('data.csv','a+',encoding='utf-8',newline='') as csvfile:

filename = ['first_name','last_name']

# 寫入列標題

writer = csv.dictwriter(csvfile,fieldnames=filename)

writer.writeheader()

writer.writerow()

writer.writerow()

writer.writerow()

python內建json包提供了四個函式:dumps、dump、loads、load。不帶s的負責檔案與字典的轉換。帶s的負責字串和字典的轉換。

字典到字串 string json.dumps(dict)
import json

test_str = json.dumps()

字串到字典 dict json.loads(string)
import json

test_dict = json.loads("")

字典到json檔案 json.dump(dict, file)
import json

with open("test.json","w") as f:

json.dump(, f)

json檔案到字典 dict json.load(file)
import json

with open("test.json",'r') as f:

test_dict = json.load(f)

gff檔案 pyhton讀寫資料檔案

1 開啟檔案獲取檔案物件 2 操作檔案 3 關閉檔案 fr open test.txt r 開啟檔案ff fr.read 讀取檔案所有內容 不建議使用,如果檔案內容巨大,記憶體會爆 print ff 檔案型別 r 唯讀,預設模式 開啟資料檔案w 只寫,不可讀,若檔案不存在則建立,若存在,則刪除內容,...

Python學習筆記 3 資料檔案的讀寫

基本步驟 f open jerry.txt mode r 用open函式開啟資料,返回乙個檔案物件,後續操作均基於該檔案物件 content f.read 用read 讀取資料,且返回檔案所有內容 print content 列印檔案內容 f.close 使用完檔案要關閉,否則會被python一直占...

R語言資料檔案的讀寫

1.鍵盤輸入資料 mydata data.frame age numeric 0 gender character 0 weight numeric 0 mydata edit mydata 在物件的副本上進行操作要保留改動需賦值 mydata fix mydata 會自動保留改動 2.txt檔案 ...