0

I am trying to close a file that I read with pandas data frame in the form of

df = pd.read_csv(file_name)

and not example_file = open(file_name) (there are some solutions with this case)

so I am trying to close the file after reading it or even writing to it. I am aware that python automatically closes back the file but while running unit tests, it throws resource allocation warnings, so in order to get rid of those warnings I need to have the files closed.

I have tried using storing the file name for example

file_name = "randomfile.csv"

and then tried doing

file_name.close()

but this does not work. I have also tried using

df.close()

but that does not work as well.

The original problem is:

ResourceWarning: Enable tracemalloc to get the object allocation traceback

which I found out meant that I have a file opened. And this warning only shows when unit testing.

greens trial
  • 57
  • 1
  • 6
  • 1
    "I am trying to close a file that I read with pandas...I am aware that python automatically closes back the file but while running unit tests, it throws resource allocation warnings" It sounds like you encountered a problem and thought of a possible solution which you are now asking about how to do. You should instead show the original problem so we can help you solve that directly. Please [edit] your question to show a [mcve] that produces these warnings you mention. – Code-Apprentice Jul 15 '22 at 21:14
  • Does this align with your issues? https://stackoverflow.com/questions/39100971/how-do-i-release-memory-used-by-a-pandas-dataframe – Nicholas Hansen-Feruch Jul 15 '22 at 22:44
  • 1
    Please post exact code block that reproduces the error not isolated line snippets and not just your thought process on the issue. Most pandas IO processes like `read_csv` that reads/writes a physical file will handle the IO closing operation without the user needed to do it. Please post actual code for us to help. – Parfait Jul 16 '22 at 00:07
  • Thank you for your edits. We still need some code that causes the warning you are asking about. Please read [mcve] for tips on creating a good code example. – Code-Apprentice Jul 18 '22 at 21:21

0 Answers0