pandas 使用 to_csv() 后关闭文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27370046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Closing file after using to_csv()
提问by knop
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?
我是 python 新手,到目前为止我喜欢 ipython notebook 学习。我是否使用 to_csv() 函数将 Pandas 数据帧写出到文件中。我想打开 csv 以查看它在 excel 中的外观,它只能以只读模式打开,因为它仍在被另一个人使用如何关闭文件?
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?
这将写出文件没问题,但是当我在 excel 中“检查”它时,我收到只读警告。这也给我带来了一个更大的问题。有没有办法查看python当前正在使用/触摸哪些文件?
回答by knop
@rpattiso thank you.
@rpattiso 谢谢。
try opening and closing the file yourself:
尝试自己打开和关闭文件:
outfile = open(path+'filename.csv', 'wb')
df.to_csv(outfile)
outfile.close()
回答by yeaske
With context manager, you don't have to handle the file resource.
使用上下文管理器,您不必处理文件资源。
with open("thefile.csv", "w") as f:
df.to_csv(f)
回答by Mike Zygal
The newest pandas to_csv closes the file automatically when it's done.
最新的pandas to_csv 完成后会自动关闭文件。

