Python,处理目录中的文件安全吗?

2024-03-29 09:12:04 发布

您现在位置:Python中文网/ 问答频道 /正文

(Python3)

我有一个进程,将入站文件放入一个目录(不是用Python编写的)。你知道吗

单独的Python应用程序定期处理目录中的所有文件,如下所示:

def getfilestobeprocessed(path):
    filestobeprocessed = []
    for dirpath, dirnames, filenames in os.walk(path):
        for filename in filenames:
            filestobeprocessed.append({ "filename": filename, "dirpath": dirpath })
    return filestobeprocessed

我关心的是,如果入站过程是在编写一个大文件的过程中完成的,那该怎么办。我的Python脚本将做什么?当它真的应该只处理入站处理器已完成写入的文件时,它会开始处理该文件吗?我应该在处理文件之前检测文件是否已打开吗?你知道吗

我会考虑使用Pyinotify,除非这个家伙批评它http://www.serpentine.com/blog/2008/01/04/why-you-should-not-use-pyinotify/


Tags: 文件pathin目录应用程序for进程过程
3条回答

或许操作系统可以告诉您另一个进程是否有该文件。你知道吗

一个很好的解决方案是,在60秒之后,如果文件没有更改,那么写入文件的内容就不再这样做了。看看http://docs.python.org/3/library/os.html#os.stat。你知道吗

当你打开(或重命名,删除,…)文件作为你处理它的一部分,你会得到一个“文件正在使用”错误。在windows上是代码32。如果并且当您看到这个错误时,不要处理这个文件-它将在下一次遍历时得到处理。你知道吗

使用锁定文件。你知道吗

所以。当它复制它时,使用文件名.lock完成复制后,将其重命名为正确的扩展名。你知道吗

然后写一个if语句,比如

def getfilestobeprocessed(path):
    filestobeprocessed = []
    for dirpath, dirnames, filenames in os.walk(path):
        for filename in filenames:
            if !filename.endswith(.lock):
                filestobeprocessed.append({ "filename": filename, "dirpath": dirpath })
    return filestobeprocessed

相关问题 更多 >