Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing file after using to_csv()

Tags:

python

pandas

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?

like image 910
knop Avatar asked Dec 09 '14 01:12

knop


2 Answers

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)
like image 158
yeaske Avatar answered Oct 20 '22 23:10

yeaske


@rpattiso thank you.

try opening and closing the file yourself:

outfile = open(path+'filename.csv', 'wb')
df.to_csv(outfile)
outfile.close()     
like image 43
knop Avatar answered Oct 20 '22 23:10

knop