I'm trying to Batch Edit all JSON files within a folder, and saving each of them as new JSON all at once, instead of doing each one.
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)
When I try to run the batchRun function, it gives me an error
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'
And I know for sure simple_json.txt and other files are within that folder that I defined, so I'm not sure what's happening.
os.listdir
gives you a list of file names , not file paths. You can use os.path.join
to get the full file path:
def batchRun(foldername):
for f in os.listdir(foldername):
new_json(os.path.join(foldername, f))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.