[英]How do i save .json files in specific folder in python
I am using python and I wrote script, that makes from.csv a.json file... it works great but i would like to save those json files into different folder.我正在使用 python 并编写了脚本,该脚本来自.csv a.json 文件......它工作得很好,但我想将这些 Z4636DEEC76ECDF24D6 文件保存到不同的文件夹中。
Where do I write path?我在哪里写路径?
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)
You need to specify the full path of the json file.您需要指定 json 文件的完整路径。
Now you are just put the name of the file and the result of this is that the file is written in the same directory.现在您只需输入文件的名称,结果就是文件被写入同一目录中。
Try to do something like this;尝试做这样的事情;
with open("my/path/{}".format(jsonfile), 'w') as f:
json.dump(rows, f,indent=4)
You might use os.path.join
for this as follows, for example例如,您可以按如下方式使用
os.path.join
jsondir = "jsons"
with open(os.path.join(jsondir,jsonfile), 'w') as f:
json.dump(rows, f,indent=4)
disclaimer: I assume jsons
catalog does already exists免责声明:我假设
jsons
目录确实已经存在
Here are a few useful hacks:以下是一些有用的技巧:
Using os
and __file__
you can consitently (OS independent) get a file's directory使用
os
和__file__
您可以始终如一地(独立于操作系统)获取文件的目录
FILE_DIR: str = os.path.dirname(os.path.abspath(__file__))
Getting to parent folders can be done with pathlib
可以使用
pathlib
访问父文件夹
from pathlib import Path
PARENT_DIR: str = Path(FILE_DIR).parent.as_posix()
Finally, you can get the user's home directory via os.path.expanduser("~")
.最后,您可以通过
os.path.expanduser("~")
获取用户的主目录。
Once you have the folder you want, the rest should be straightforward.获得所需文件夹后,rest 应该很简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.