python - 在Python中循环处理后移动文件的权限错误

标签 python json

我有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/

相关文章:

java - 如何从包含未经修改的数组的 String JSON 中获取 java 中 JSON 对象的 String[] 数组

javascript - 如何传递内联 JSON 而不是 URL 路径

Python交互模式历史和方向键

c# - C#中的JSON解码

python - TKinter - 如何从 Entry() 添加两个数字

python - 创建一个基本的Python接口(interface)来保存用鼠标绘制的图像

java - 尝试从 java webservice 中的 json 对象获取值时出现异常

json - 如何将 JSON 数据 append 到现有的 JSON 文件 node.js

python - 十四行诗导入在 : 'from graphs import Sonnet' 上失败

Python-使用列表作为函数参数