Python pandas - read_csv 是否保持文件打开?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29416968/
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-09-08 15:38:27  来源:igfitidea点击:

Python pandas - Does read_csv keep file open?

pandas

提问by nivniv

When using pandas read_csv()method, does it keep the file open or it closes it (discard the file descriptor)?

使用 pandasread_csv()方法时,它是保持文件打开还是关闭它(丢弃文件描述符)?

If it keeps it, how do I close it after I finish using the dataframe?

如果它保留它,我如何在使用完数据框后关闭它?

采纳答案by Andy Hayden

If you pass it an open file it will keep it open (reading from the current position), if you pass a string then read_csvwill open and close the file.

如果您传递一个打开的文件,它将保持打开状态(从当前位置读取),如果您传递一个字符串,read_csv则将打开和关闭文件。



In python if you open a file but forget to close it, python will close it for you at the end of the function block (during garbage collection).

在 python 中,如果你打开一个文件但忘记关闭它,python 会在函数块的末尾(在垃圾收集期间)为你关闭它。

def foo():
    f = open("myfile.csv", "w")
    ...
    f.close()  # isn't actually needed

i.e. if you call a python function which opens a file, unless the file object is returned, the file is automagicallymatically closed.

即,如果您调用打开文件的python 函数,除非返回文件对象,否则文件将自动神奇地关闭。

Note: The preferred syntax is the withblock (which, as well as closing fat the end of the withblock, defines the fvariable only inside the withblock):

注意:首选语法是with块(它以及fwith块末尾关闭,f仅在with块内定义变量):

def foo():
    with open("myfile.csv", "w") as f:
        ...