简体   繁体   English

在Python中保存json文件时如何定义文件夹名称?

[英]How to define folder name when saving json file in Python?

How to define folder name when saving JSON file?保存 JSON 文件时如何定义文件夹名称? I tried to add myfoldername inside open() , but did not work.我试图在open()中添加myfoldername ,但没有奏效。 Also tried to myfoldername/myfilename in filename definition还尝试在文件名定义中使用myfoldername/myfilename

Error:错误:

TypeError: an integer is required (got type str)

Code:代码:

import json

# Testing file save
dictionary_data = {"a": 1, "b": 2}

filename = "myfilename" +  time.strftime("%Y%m%d-%H%M%S") + ".json"
a_file = open("myfoldername",filename, "w")
json.dump(dictionary_data, a_file)
a_file.close()

This should do the trick.这应该可以解决问题。

  • Use pathlib to manage paths使用pathlib管理路径
  • Create the parent dir if not exist with mkdir如果不存在,则使用mkdir创建父目录
  • Open the file thanks to the with statement通过with语句打开文件
import json
import time
from pathlib import Path

# Testing file save
dictionary_data = {"a": 1, "b": 2}

filename = Path("myfilename") / Path(f"{time.strftime('%Y%m%d-%H%M%S')}.json")
# create the parent dir if not exist
filename.parent.mkdir(parents=True, exist_ok=True)

with open(filename, "w") as a_file:
    json.dump(dictionary_data, a_file)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 python 的目标文件夹中保存名称包含 / 的文件 - Saving file with a name containing / at the destination folder in python 将每个 python 执行的图像保存在以序列号作为文件名的文件夹中 - Saving image of every python execution in a folder with a serial number as file name 将数据保存到 Python 中的 JSON 文件时出错 - Error when saving data to a JSON file in Python 如何在调整图像大小并将其保存到另一个文件夹时保留图像的文件名? - How do I keep the file name of an image when resizing it and saving it to another folder? 如何在python中获取文件夹名称和文件名 - how to get a folder name and file name in python 如何定义python文件名过滤器模式 - How to define python file name filter pattern 如果在文本文件中找到特定的字符串,则从文件夹内读取文本文件并保存文件夹的名称-Python - Reading a text file from within a folder and saving the name of the folder if a particular string is found in the text file - Python 如何对文件名为python的文件夹中的文件进行排序 - How to sort files in a folder with file name in python 如何创建 JSON 对象文件夹名称和文件名称视图 - How to create JSON objects Folder name and File Name View 保存在循环python / pandas中时的其他文件名 - Different file name when saving in loop python/pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM