【问题标题】:How do i save .json files in specific folder in python如何将 .json 文件保存在 python 的特定文件夹中
【发布时间】:2022-01-19 08:48:15
【问题描述】:

我正在使用 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)

【问题讨论】:

  • open() 的文档说file is a path-like object giving the pathname (absolute or relative to the current working directory)。也就是说,您可以在对open 的调用中指定要保存文件的绝对(或相对)路径。 docs.python.org/3/library/functions.html#open

标签: python json csv


【解决方案1】:

您需要指定json文件的完整路径。
现在你只需输入文件名,结果就是文件写在同一个目录中。

尝试做这样的事情;

with open("my/path/{}".format(jsonfile), 'w') as f:
    json.dump(rows, f,indent=4)

【讨论】:

    【解决方案2】:

    你可以使用os.path.join,例如

    jsondir = "jsons"
    with open(os.path.join(jsondir,jsonfile), 'w') as f:
        json.dump(rows, f,indent=4)
    

    免责声明:我假设 jsons 目录确实已经存在

    【讨论】:

      【解决方案3】:

      这里有一些有用的技巧:

      使用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("~")获取用户的主目录。

      一旦你有了你想要的文件夹,剩下的就应该很简单了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-28
        • 1970-01-01
        相关资源
        最近更新 更多