检查文件是否在 Python 中打开

在我的应用程序中,我写入一个 Excel 文件。写入之后,用户可以通过打开文件来查看它。但是,如果用户忘记在进一步写入之前关闭文件,则应该出现一条警告消息。所以我需要一种方法来检查这个文件是打开前的写作过程。你能给我提供一些 Python 代码来完成这个任务吗?

209798 次浏览

您可以使用 with open("path") as file:,以便它自动关闭,否则,如果它在另一个进程中打开,您可以尝试 在 Tims 示例中,您应该使用除 IOError 之外的方法来避免忽略代码中的任何其他问题:)

try:
with open("path", "r") as file: # or just open
# Code here
except IOError:
# raise error or print

我假设您正在写入文件,然后关闭它(这样用户就可以在 Excel 中打开它) ,然后,在为追加/写操作重新打开它之前,您想检查该文件是否在 Excel 中仍然打开?

你可以这样做:

while True:   # repeat until the try statement succeeds
try:
myfile = open("myfile.csv", "r+") # or "a+", whatever you need
break                             # exit the loop
except IOError:
input("Could not open file! Please close Excel. Press Enter to retry.")
# restart the loop


with myfile:
do_stuff()

如果您只关心当前进程 ,那么一种简单的方法是使用 file object 属性“ close”

f = open('file.py')
if f.closed:
print 'file is closed'

这将无法检测文件是否被其他进程打开!

来源: http://docs.python.org/2.4/lib/bltin-file-objects.html

只能放在窗户上

其他提供的例子都不适合我在处理这个特定的问题时使用 Excel on windows 10。我能想到的唯一其他选择是尝试临时重命名包含该文件的文件或目录,然后重命名回来。

import os


try:
os.rename('file.xls', 'tempfile.xls')
os.rename('tempfile.xls', 'file.xls')
except OSError:
print('File is still open.')

吸毒

try:
with open("path", "r") as file:#or just open

当文件被其他进程打开时(即用户手动打开) ,可能会造成一些麻烦。 您可以使用 win32com 库解决您的问题。 下面的代码检查是否打开了任何 Excel 文件,如果没有一个与您的特定 Excel 文件的名称匹配,则打开一个新的 Excel 文件。

import win32com.client as win32
xl = win32.gencache.EnsureDispatch('Excel.Application')


my_workbook = "wb_name.xls"
xlPath="my_wb_path//" + my_workbook




if xl.Workbooks.Count > 0:
# if none of opened workbooks matches the name, openes my_workbook
if not any(i.Name == my_workbook for i in xl.Workbooks):
xl.Workbooks.Open(Filename=xlPath)
xl.Visible = True
#no workbooks found, opening
else:
xl.Workbooks.Open(Filename=xlPath)
xl.Visible = True


'xl.Visible = True is not necessary, used just for convenience'

希望这个能帮上忙

if myfile.closed == False:
print("File is still open ################")

只要使用这个函数。它将关闭任何已经打开的 Excel 文件

import os


def close():


try:
os.system('TASKKILL /F /IM excel.exe')


except Exception:
print("KU")


close()

如果上述方法损坏了您的 Excel 文件,请尝试此方法。

此函数尝试用自己的名称重命名文件。如果文件已经打开,操作系统将拒绝编辑,并引发 OSERror 异常。它不会触及内部代码,因此不会损坏您的 Excel 文件。LMK 如果对你有用的话。

def check_file_status(self):
try:
os.rename("file1.xlsx", "file1.xlsx")
print("File is closed.")
except OSError:
print("File is opened.")