我有3个json文件需要用python解析。
文件1.jasn 文件2.json 文件3.json
我故意破坏了 file3.json 中的格式,因此它实际上并不包含正确的 json 格式。
我的代码:
import os, json, shutil
fileRoot = 'C:/root/python/'
inputFiles = fileRoot + 'input/'
processed_folder = fileRoot + 'processed/'
error_folder = fileRoot + 'error/'
print("processFiles")
print('inputfiles = ' + inputFiles)
if any(File.endswith(".json") for File in os.listdir(inputFiles)):
json_files = [pos_json for pos_json in os.listdir(inputFiles) if pos_json.endswith('.json')]
print('--------------------FILES IN DIRECTORY----------------------')
print(json_files)
print( '--------------------FILE LOOPING----------------------------')
for eachfile in json_files:
print(eachfile)
with open((inputFiles + eachfile), 'r') as f:
try:
data = json.load(f)
except :
shutil.move((inputFiles + eachfile), error_folder)
这个想法是,如果它不解析 JSON,则应将文件移动到另一个名为“error”的文件夹
但是,我不断收到错误,例如:
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:/Python/input/file3.json' -> 'C:/root/Python/input/file3.json'
为什么会发生这种情况?
最佳答案
您正在打开文件,它们将保持打开状态,直到 with
block 退出。
作为解决方法,您可以将要移动的文件存储在列表中:
move_to_error = []
move_to_valid = []
for eachfile in json_files:
print(eachfile)
with open((inputFiles + eachfile), 'r') as f:
try:
data = json.load(f)
# if we have an exception in the previous line,
# the file will not be appended to move_to_valid
move_to_valid.append(eachfile)
except:
move_to_error.append(eachfile)
for eachfile in move_to_error:
shutil.move((inputFiles + eachfile), error_folder)
关于python - 在Python中循环处理后移动文件的权限错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57035942/