Python 有没有办法关闭该文件已经打开的文件。
或者至少显示一个文件已打开的弹出窗口或一个自定义的书面错误消息弹出窗口
permission error.
要避免:
PermissionError: [Errno 13] Permission denied: 'C:\\zf.csv'
我见过很多通过 python 打开文件然后关闭它的解决方案。 但就我而言。 假设我将 csv 打开,然后尝试运行该作业。
如何才能关闭当前打开的 csv?
我已经尝试了以下变体,但似乎没有一个起作用,因为他们期望我已经在早些时候通过 python 打开了 csv。 我怀疑我把这件事复杂化了。
f = 'C:\\zf.csv'
file.close()
AttributeError: 'str' object has no attribute 'close'
这会产生错误,因为没有引用打开文件而只是字符串。
甚至..
theFile = open(f)
file_content = theFile.read()
# do whatever you need to do
theFile.close()
以及:
fileobj=open('C:\\zf.csv',"wb+")
if not fileobj.closed:
print("file is already opened")
如何关闭已打开的 csv?
我能想到的唯一解决方法是添加一个消息框,尽管我似乎无法让它检测文件。
filename = "C:\\zf.csv"
if not os.access(filename, os.W_OK):
print("Write access not permitted on %s" % filename)
messagebox.showinfo("Title", "Close your CSV")
您也可以尝试将文件复制到临时文件中,并随意打开/关闭/删除它。不过,它要求您具有对原件的读取权限。
在此示例中,我有一个只写文件“test.txt”(chmod 444),如果我尝试直接写入它,它会抛出“权限被拒绝”错误。我将其复制到具有“777”权限的临时文件,以便我可以用它做我想做的事情:
import tempfile, shutil, os
def create_temporary_copy(path):
temp_dir = tempfile.gettempdir()
temp_path = os.path.join(temp_dir, 'temp_file_name')
os.chmod(temp_path, 0o777); # give full access to the tempfile so we can copy
shutil.copy2(path, temp_path) # copy the original into the temp one
os.chmod(temp_path, 0o777); # replace permissions from the original file
return temp_path
path = "./test.txt" # original file
copy_path = create_temporary_copy(path) # temp copy
with open(copy_path, "w") as g: # can do what I want with it
g.write("TEST\n")
以下代码可有效关闭打开指定 CSV 文件的所有 Microsoft Excel 实例,同时确保其仅针对 CSV 文件并在整个过程中提供用户反馈。
确保将
"path/to/your/file.csv"
替换为您要检查的 CSV 文件的实际路径。
import psutil
def close_csv_in_excel(file_path):
found_process = False # Flag to check if we found any process using the file
# Ensure the file path is a CSV
if not file_path.lower().endswith('.csv'):
print("The specified file is not a CSV file.")
return
# Iterate over all running processes
for proc in psutil.process_iter(['pid', 'name']):
try:
# Check if the process name is 'EXCEL.EXE'
if proc.info['name'].lower() == 'excel.exe':
# Iterate through open files for the Excel process
for file in proc.open_files():
if file.path == file_path:
print(f"Terminating Excel process {proc.info['name']} (PID: {proc.info['pid']}) to close {file_path}")
proc.terminate() # or proc.kill() to force kill
found_process = True
break # Exit the inner loop, as we found the process
except psutil.AccessDenied:
# Handle the AccessDenied exception
print(f"Access denied for process {proc.info['name']} (PID: {proc.info['pid']})")
except psutil.NoSuchProcess:
# Handle the case where the process no longer exists
print(f"Process with PID {proc.info['pid']} no longer exists.")
if not found_process:
print(f"No open Excel processes found for {file_path}")
if __name__ == "__main__":
# Example usage
csv_file_to_close = "path/to/your/file.csv" # Change to the CSV file you want to check
close_csv_in_excel(csv_file_to_close)
CSV 文件检查:
.csv
结尾。如果没有,它会打印一条消息并提前返回。进程名称过滤:
EXCEL.EXE
(不区分大小写)。这可确保仅考虑 Excel 进程。文件路径比较:
终止逻辑:
found_process
标志设置为 True
。用户反馈:
f = open("C:/Users/amol/Downloads/result.csv", "r")
print(f.readlines()) #just to check file is open
f.close()
# here you can add above print statement to check if file is closed or not. I am using python 3.5