关闭文件上的 Python ValueError I/O 操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34040619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:23:32  来源:igfitidea点击:

Python ValueError I/O operation on closed file

pythoncsvpandasio

提问by Duy Bui

I know this sounds a common error which has been asked multiple times on stackoverflow. However, I am pretty sure my issue is new as I read through almost the related topics.

我知道这听起来是一个常见的错误,在 stackoverflow 上被多次询问过。但是,我很确定我的问题是新的,因为我几乎通读了相关主题。

I have two files as follows:

我有两个文件如下:

ALL_USER_PATH = 'all.csv'
NEW_USER_PATH = 'new.csv'

I open the "all" file for reading first

我先打开“所有”文件进行阅读

with open(ALL_USER_PATH, "r") as f:
    df = pd.read_csv(f) #pd is pandas
    f.close()

Next, I delete the content of the "new" file and get ready to write new data to it

接下来,我删除“新”文件的内容并准备向其中写入新数据

if os.path.isfile(NEW_USER_PATH):
    os.remove(NEW_USER_PATH)

Write to it and it works fine

写信给它,它工作正常

with open(NEW_USER_PATH, "a") as csv_n:
    #writer_n is to write new users
    writer_n = csv.writer(csv_n, delimiter=",", lineterminator='\n')
    for user in customer_records:         
        if checkExistence(df): # a method I wrote before
            continue
        else:    
            writer_n.writerow([data_to_be_written])

Next, I delete the "all" file and write new data to it

接下来,我删除“所有”文件并向其写入新数据

if os.path.isfile(ALL_USER_PATH):
    os.remove(ALL_USER_PATH)

with open(ALL_USER_PATH, "a") as csv_a:
    writer_a = csv.writer(csv_n, delimiter=",", lineterminator='\n')

    for user in customer_records:
        writer_a.writerow([all_data_to_be_written])

The error

错误

"ValueError i/o operation on closed file"

“关闭文件上的 ValueError i/o 操作”

is thrown herein at the last line to write data to the "all" file. I think it is because I opened it before, but I do remember to close it after reading the data, don't I? Could somebody please let me know what the problem is?

在最后一行抛出这里将数据写入“所有”文件。我想是因为我之前打开过它,但我确实记得在阅读数据后关闭它,不是吗?有人可以让我知道问题是什么吗?

回答by TheOneWhoLikesToKnow

I also had that error but found another question with an answer and it worked.

我也有这个错误,但找到了另一个有答案的问题,它奏效了。

After you leave the indented block under with open (csv file.csv) as csv:it will close the file.

在您离开缩进块后with open (csv file.csv) as csv:,它将关闭文件。

with open('ALL_USER_PATH','a') as csv_a:
    writer_a = csv.writer(csv_n, delimiter=",", lineterminator='\n')
    # Here the file stays open
# Here the file is closed

I hope I managed to help.

我希望我能帮上忙。