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?
The pandas. read_csv is used to load a CSV file as a pandas dataframe. In this article, you will learn the different features of the read_csv function of pandas apart from loading the CSV file and the parameters which can be customized to get better output from the read_csv function.
The difference between read_csv() and read_table() is almost nothing. In fact, the same function is called by the source: read_csv() delimiter is a comma character. read_table() is a delimiter of tab \t .
Narrow answer: yes. You can provide the engine='python' and nrows=N arguments to pick up where pandas's reader leaves off in a text file, or to use pd. read_csv multiple times for a single open file object. Pandas searches the file for separators such as commas newlines.
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.
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
i.e. if you call a python function which opens a file, unless the file object is returned, the file is automagicallymatically closed.
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: ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With