簡體   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