【发布时间】:2011-10-13 03:36:17
【问题描述】:
在我的应用程序中,我写入了一个 excel 文件。写入后,用户可以通过打开文件来查看文件。但是,如果用户在进一步写入之前忘记关闭文件,则会出现警告消息。所以我需要一种在写入过程之前检查这个文件是否打开的方法。你能给我一些python代码来完成这个任务吗?
【问题讨论】:
在我的应用程序中,我写入了一个 excel 文件。写入后,用户可以通过打开文件来查看文件。但是,如果用户在进一步写入之前忘记关闭文件,则会出现警告消息。所以我需要一种在写入过程之前检查这个文件是否打开的方法。你能给我一些python代码来完成这个任务吗?
【问题讨论】:
只需使用此功能。它将关闭任何已经打开的 excel 文件
import os
def close():
try:
os.system('TASKKILL /F /IM excel.exe')
except Exception:
print("KU")
close()
【讨论】:
if myfile.closed == False:
print("File is still open ################")
【讨论】:
.closed 属性的this existing answer 的副本。
我假设您正在写入文件,然后关闭它(以便用户可以在 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()
【讨论】:
您可以使用with open("path") as file: 使其自动关闭,否则如果它在另一个进程中打开,您可以尝试
如在 Tims 示例中,您应该使用 except IOError 来不忽略代码的任何其他问题:)
try:
with open("path", "r") as file: # or just open
# Code here
except IOError:
# raise error or print
【讨论】:
except。此外,try 块的范围太广 - Shansal 想检查文件是否可以打开。写入文件时的错误处理(或with 块中发生的任何其他事情)应该是分开的。
使用
try:
with open("path", "r") as file:#or just open
当文件被其他进程打开时(即用户手动打开它)可能会导致一些麻烦。 您可以使用 win32com 库解决您的问题。 下面的代码检查是否打开了任何 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'
希望这会有所帮助
【讨论】:
在 Windows 10 上使用 excel 处理这个特定问题时,没有其他提供的示例对我有用。我能想到的唯一其他选择是尝试暂时重命名包含该文件的文件或目录,然后重命名它返回。
import os
try:
os.rename('file.xls', 'tempfile.xls')
os.rename('tempfile.xls', 'file.xls')
except OSError:
print('File is still open.')
【讨论】:
如果你只关心当前进程,一个简单的方法是使用文件对象属性“关闭”
f = open('file.py')
if f.closed:
print 'file is closed'
这不会检测文件是否被其他进程打开!
【讨论】:
.closed 属性检查文件是否被当前 Python 进程关闭。它不检查文件是否被任何其他进程打开或关闭。
ipython shell,然后打开一个 f = open('foo.txt', 'w'),另一个打开 f = open('foo.txt', 'r')。然后是f.closed is False,但第二个终端中的f.close() 足以将其变成f.closed is True。