Python未关闭文件,Windows 10
正在Jupyter中读取.csv文件:Python未关闭文件,Windows 10,python,python-3.x,windows-10,jupyter-notebook,Python,Python 3.x,Windows 10,Jupyter Notebook,正在Jupyter中读取.csv文件: filename = "myfile.csv" start_pd = time.time() try: with open (filename, 'rb') as file: reader = pd.read_csv(filename, chunksize=10000, error_bad_lines=False, header=None) df = pd.concat([x for x in reader], ig
filename = "myfile.csv"
start_pd = time.time()
try:
with open (filename, 'rb') as file:
reader = pd.read_csv(filename, chunksize=10000, error_bad_lines=False, header=None)
df = pd.concat([x for x in reader], ignore_index=True)
df.columns = dfcolslist
file.close #also tried reader.close() and file.closed
print("{} read successfully in {:.2f} secs".format(filename, time.time() - start_pd))
except IOError:
print("could not read {}".format(filename))
cmd错误消息:
>ren“myfile.csv”date\u myfile.csv
进程无法访问该文件,因为其他进程正在使用该文件。
GUI错误消息:
该操作无法完成,因为该文件已在Python中打开
因为您正在将字符串传递给pd.read\u csv它尝试打开一个已经打开的文件
它说
filepath\u或\u缓冲区:str、path对象或类文件对象任何有效
字符串路径是可接受的。字符串可以是URL。有效URL
方案包括http、ftp、s3和文件。对于文件URL,主机是
预期。本地文件可以是:file://localhost/path/to/table.csv.
如果要传入一个路径对象,则
pathlib.Path或py.\u Path.local.LocalPath
通过类文件对象,我们使用read()方法引用对象,例如
文件处理程序(例如,通过内置打开函数)或StringIO
要么:
- 将文件名作为字符串传递给
,并让它自己处理打开、读取和关闭文件的操作:pd.read\u csv
reader = pd.read_csv(filename, chunksize=10000, error_bad_lines=False, header=None)
- 或,使用打开的
自己打开文件,并将文件对象传递给
:pd。读取\u csv
with open (filename, 'rb') as file: reader = pd.read_csv(file, chunksize=10000, error_bad_lines=False, header=None)
在这两种情况下,您都不应该单独调用
.close()
。当使用打开时,您不应该调用close
。
注释关闭行不会改变任何东西,问题持续存在。您的问题不是“关闭文件”正如标题所示,错误消息表示它“已打开”或“正在被另一个进程使用”,即未关闭