猿问

在Python中检查文件是否未打开(其他进程未使用)

在我的应用程序中,我有以下要求:1.有一个线程将定期在文件中记录一些日志。日志文件将在一定间隔内翻转。用于保持日志文件较小。2.还有另一个线程将定期处理这些日志文件。例如:将日志文件移到其他位置,解析日志内容以生成一些日志报告。


但是,有一个条件是第二个线程无法处理用于记录日志的日志文件。在代码方面,伪代码类似如下:


#code in second thread to process the log files

for logFile in os.listdir(logFolder):

     if not file_is_open(logFile) or file_is_use(logFile):

          ProcessLogFile(logFile) # move log file to other place, and generate log report....

那么,如何检查文件是否已打开或被其他进程使用?我在互联网上做了一些研究。并得到一些结果:


try:

   myfile = open(filename, "r+") # or "a+", whatever you need

except IOError:

    print "Could not open file! Please close Excel!"

我尝试了此代码,但是无论我使用“ r +”还是“ a +”标志,该代码均无效


try:

   os.remove(filename) # try to remove it directly

except OSError as e:

    if e.errno == errno.ENOENT: # file doesn't exist

        break

该代码可以工作,但是无法达到我的要求,因为我不想删除该文件以检查它是否打开。


慕工程0101907
浏览 1573回答 3
3回答

杨魅力

我喜欢Daniel的回答,但我意识到将文件重命名为它已经拥有的名称更安全,更简单。这解决了他回答中提到的问题。我只是在评论中说过这一点,但我没有要点。这是代码:import osf = 'C:/test.xlsx'if os.path.exists(f):    try:        os.rename(f, f)        print 'Access on file "' + f +'" is available!'    except OSError as e:        print 'Access-error on file "' + f + '"! \n' + str(e)

不负相思意

您可以使用下一个函数检查文件上是否有句柄(请记住将完整路径传递给该文件):import psutildef has_handle(fpath):    for proc in psutil.process_iter():        try:            for item in proc.open_files():                if fpath == item.path:                    return True        except Exception:            pass    return False
随时随地看视频慕课网APP

相关分类

Python
我要回答