Closing file after using to_csv()

后端 未结 3 806
猫巷女王i
猫巷女王i 2020-12-19 19:37

I am new to python and so far I am loving the ipython notebook for learning. Am I using the to_csv() function to write out a pandas dataframe out to a file. I wanted to o

相关标签:
3条回答
  • 2020-12-19 20:11

    @rpattiso thank you.

    try opening and closing the file yourself:

    outfile = open(path+'filename.csv', 'wb')
    df.to_csv(outfile)
    outfile.close()     
    
    0 讨论(0)
  • 2020-12-19 20:27

    This is the better way of doing it. With context manager, you don't have to handle the file resource.

    with open("thefile.csv", "w") as f:
        df.to_csv(f)
    
    0 讨论(0)
  • 2020-12-19 20:29

    The newest pandas to_csv closes the file automatically when it's done.

    0 讨论(0)
提交回复
热议问题