csv, txt, json 寫文件 python3環境

 

遍歷子目錄獲取文件

import os

for dir, dirs, files in (os.walk) 
    print(os.path.join(dir, dirs, files))

 

 

1. Json

import json

my_details = {
    'name': 'John Doe',
    'age': 29
}

with open('personal.json', 'w') as json_file:
    json.dump(my_details, json_file)

 

2. txt

逐行寫入

with open('do_re_mi.txt', 'w') as f:
    f.write('Doe, a deer, a female deer\n')
    f.write('Ray, a drop of golden sun\n')

一次寫入

with open('browsers.txt', 'w') as f:
    web_browsers = ['Firefox\n', 'Chrome\n', 'Edge\n']
    f.writelines("%s\n" % line for line in web_browsers)
with open('browsers.txt', 'w') as f:
    web_browsers = ['Firefox\n', 'Chrome\n', 'Edge\n']
    f.writelines(web_browsers)

3. csv

import csv weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] 

sales = ['10', '8', '19', '12', '25'] 

with open('sales.csv', 'w') as csv_file: 
    csv_writer = csv.writer(csv_file, delimiter=',') 
    csv_writer.writerow(weekdays) 
    csv_writer.writerow(sales)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章