![](/img/trans.png)
[英]New to Python 3.4+ Scripting and writing JSON text files and saving them
[英]Python 3.4+ Scripting regarding to Batch Editing JSON and Saving them
我正在尝试批量编辑文件夹中的所有JSON文件,并将它们全部一次保存为新的JSON,而不是每次都保存。
def new_json(filename):
with open(filename, 'r+') as f:
json_data = json.load(f)
somefunction()
f.seek(0)
base, ext = os.path.splitext(filename)
out_file = open(base + '_expand' + ext, 'w')
json.dump(room_data, out_file, indent=4)
def batchRun(foldername):
for f in os.listdir(foldername):
new_json(f)
folder = 'testing'
batchRun(folder)
当我尝试运行batchRun函数时,它给我一个错误
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
batchRun(folder)
File "<pyshell#8>", line 3, in batchRun
new_json(f)
File "<pyshell#6>", line 2, in new_json
with open(filename, 'r+') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'simple_json.txt'
而且我确定simple_json.txt和其他文件位于我定义的文件夹中,因此我不确定发生了什么。
os.listdir
为您提供文件名列表,而不是文件路径。 您可以使用os.path.join
来获取完整的文件路径:
def batchRun(foldername):
for f in os.listdir(foldername):
new_json(os.path.join(foldername, f))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.