Python pandas -read_csv是否保持文件打开状态? [英] Python pandas - Does read_csv keep file open?

查看:480
本文介绍了Python pandas -read_csv是否保持文件打开状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

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

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

在python中,如果您打开文件却忘记关闭文件,则python会在功能块末尾(在垃圾回收期间)为您关闭文件.

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).

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

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

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

注意:首选语法是with块(在with块的结尾处以及在with块的结尾处关闭f,仅在with块内部定义了f变量):

Note: The preferred syntax is the with block (which, as well as closing f at the end of the with block, defines the f variable only inside the with block):

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

这篇关于Python pandas -read_csv是否保持文件打开状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆