【问题标题】:Close already open csv in Python在 Python 中关闭已经打开的 csv
【发布时间】:2018-05-15 10:36:29
【问题描述】:

有没有办法让 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")

【问题讨论】:

  • 你可以使用try/except来捕捉这个错误并做一些事情
  • 您不能关闭在其他程序中打开的文件,因为系统控制它以确保安全。但问题可能是因为您将文件放在不应该使用的文件夹中 - 每个用户都有自己的文档文件夹。您是否尝试将其保存在您的文件夹或桌面上?
  • 顺便说一句:Permission denied 不一定表示该文件已打开,但您无权打开此文件夹中的文件。
  • @furas 对我来说,当我已经打开该文件时,我会在 Windows 上得到这个。
  • 不能把文件复制到temporary file,这样就可以随意打开、关闭、删除了吗?

标签: python python-3.x csv tkinter


【解决方案1】:
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

【讨论】:

  • 如果close()之前有错误/异常,则不会运行close(),也不会关闭。
  • 这里可以添加try except方法
  • 但你没有在例子中使用它
【解决方案2】:

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

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

【讨论】:

  • 这似乎没有关闭任何东西。使用 open('C:\\1\\c.csv') 作为 theFile:file_content = theFile.read() theFile.close()
  • 不要调用theFile.close(),它会在with 块的末尾自动完成。如果它不能,它不会强制关闭它(如果它在另一个程序中打开,你无论如何都无法实现),但它不会抛出错误并且你的程序会继续。
【解决方案3】:

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

在这个例子中,我有一个只写的文件“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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多