5

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 open the csv to see how it would look in excel and it would only open in read only mode because it was still in use by another How do I close the file?

import pandas as pd
import numpy as np
import statsmodels.api as sm
import csv

df = pd.DataFrame(file)
path = "File_location"

df.to_csv(path+'filename.csv', mode='wb')

This will write out the file no problem but when I "check" it in excel I get the read only warning. This also brought up a larger question for me. Is there a way to see what files python is currently using/touching?

knop
  • 135
  • 1
  • 2
  • 10
  • 4
    try opening and closing the file yourself, `outfile = open(path+'filename.csv', 'wb'); df.to_csv(outfile); oufile.close()` – ryanpattison Dec 09 '14 at 01:38

3 Answers3

7

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)
yeaske
  • 1,352
  • 14
  • 21
4

@rpattiso thank you.

try opening and closing the file yourself:

outfile = open(path+'filename.csv', 'wb')
df.to_csv(outfile)
outfile.close()     
cosmosis
  • 6,047
  • 3
  • 32
  • 28
knop
  • 135
  • 1
  • 2
  • 10
3

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

Mike Z.
  • 109
  • 3
  • which version? 1.1.5? Thanks – shlomiLan Dec 17 '20 at 16:44
  • I definitely used earlier but you can easily test if this works on your pandas version. Just run to_csv('some.csv') in the console and then try to modify and delete some.csv. It if allows you with your interpreter still open, it means that to_csv released the file. – Mike Z. Dec 23 '20 at 19:34