我正在使用 python 并且我撰寫了腳本,它從 .csv 生成一個 .json 檔案......它很好用,但我想將這些 json 檔案保存到不同的檔案夾中。
我在哪里寫路徑?
import csv
import json
import glob
import os
for filename in glob.glob("Csv/*.csv"):
csvfile = os.path.splitext(filename)[0]
jsonfile = csvfile '.json'
with open(csvfile '.csv') as f:
reader = csv.DictReader(f)
rows = list(reader)
with open(jsonfile, 'w') as f:
json.dump(rows, f,indent=4)
uj5u.com熱心網友回復:
您需要指定 json 檔案的完整路徑。
現在您只需輸入檔案名,結果是該檔案被寫入同一目錄中。
嘗試做這樣的事情;
with open("my/path/{}".format(jsonfile), 'w') as f:
json.dump(rows, f,indent=4)
uj5u.com熱心網友回復:
例如,您可以os.path.join按如下方式使用它
jsondir = "jsons"
with open(os.path.join(jsondir,jsonfile), 'w') as f:
json.dump(rows, f,indent=4)
免責宣告:我假設jsons目錄已經存在
uj5u.com熱心網友回復:
這里有一些有用的技巧:
使用os并且__file__您可以持續地(獨立于作業系統)獲取檔案的目錄
FILE_DIR: str = os.path.dirname(os.path.abspath(__file__))
可以使用以下方法訪問父檔案夾 pathlib
from pathlib import Path
PARENT_DIR: str = Path(FILE_DIR).parent.as_posix()
最后,您可以通過os.path.expanduser("~").
一旦你有了你想要的檔案夾,剩下的就很簡單了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/386371.html
