在python中移动之前关闭文件

在python中移动之前关闭文件

我在尝试使用shutil.move()移动文件时遇到问题,可能是因为文件仍处于打开状态。在调试器中运行它时我没有遇到问题...但是当我执行脚本时出现此错误:

WindowsError:[错误 32] 该进程无法访问该文件,因为它正在被另一个进程使用

以下是导致此问题的代码块。如何更改此代码块以避免出现此问题?

while len(args) > 0:
    outdir = args.pop()
    indir  = args.pop()
    inouts.append( (indir,outdir) )

    listFile = os.listdir(indir)
    os.chdir(indir)

    for report in listFile:
        abs_report = os.path.abspath(report)
        for line in open(abs_report):
            if header not in line:
                if ref in line:
                    shutil.move(abs_report,Pull)
                    logger.write("File " + report + " has been moved to " + Pull + " at " +  str(datetime.now()) + "\n")
                    break
                else:
                    shutil.move(abs_report,outdir)
                    logger.write("File " + report + " has been moved to " + outdir + " at " + str(datetime.now()) + "\n")
                    break

答案1

您需要在移动文件之前退出循环:

listFile = os.listdir(indir)
os.chdir(indir)

for report in listFile:
    abs_report = os.path.abspath(report)
    is_pull = None
    for line in open(abs_report):
        if header not in line:
            is_pull = (ref in line)
            break
    if is_pull is not None:
        if is_pull:
            shutil.move(abs_report,Pull)
            logger.write("File " + report + " has been moved to " + Pull + " at " +  str(datetime.now()) + "\n")
        else:
            shutil.move(abs_report,outdir)
            logger.write("File " + report + " has been moved to " + outdir + " at " + str(datetime.now()) + "\n")

相关内容