繁体   English   中英

关闭已在Python中打开的csv

[英]Close already open csv in Python

Python有没有办法关闭该文件已打开的文件。

或者至少显示一个打开该文件的弹出窗口,或者显示一个针对permission error.的自定义错误消息弹出窗口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")

尝试使用with上下文,它将在上下文结束时顺利管理close( __exit__ )操作:

with open(...) as theFile:
    file_content = theFile.read()

您也可以尝试将文件复制到临时文件,然后随意打开/关闭/删除它。 但是,它要求您具有对原始文件的读取权限。

在此示例中,我有一个仅可写的文件“ 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")
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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM