我有一个项目,是用 OOP 在单独的模块上编写的。第一个被对象导入和调用的模块是“DataLibrary”。
为了确保工作目录中存在 .csv 文件,我使用 try- except-else 语句。他们执行我上面写的这些步骤。
import pandas
import os.path
class DataLibrary:
def __init__(self):
try:
os.path.isfile("iata-codes.csv")
except FileNotFoundError:
self.data_xlsx = pandas.read_excel("iata-codes.xlsx", "Sheet1", dtype=str, index_col=None)
self.data_xlsx.to_csv("iata-codes.csv", encoding="utf-8", index=False)
self.df = pandas.read_csv("iata-codes.csv")
else:
self.df = pandas.read_csv("iata-codes.csv")
问题是,即使我知道工作目录中不存在 .csv 文件,try 语句返回 true ,它会跳过 except 语句(应该在其中创建 .csv 文件)并跳转到在 pandas 上失败的 else 语句。 read_csv 因为就像我说的,工作目录中不存在这样的 .csv 文件。
顺便说一句,我已经使用 os.getcwd 检查了 DataLibrary 的工作目录,它是我的项目目录。所以我没有在代码中使用相对/绝对文件路径,因为 .py .xlsx 和 .csv 文件都位于同一个文件夹中。
我相信这是由于 os.path.isfile 语句造成的。当我搜索它时,我发现即使文件不存在,如果文件已在内存中打开,它也会返回 True 。我之前确实在不同的项目文件夹中使用过这个 .csv 文件,并且我没有使用“with”语句在使用后关闭它。也许我应该清除 IDE 当前打开的文件内存来解决这个问题。有什么办法可以做到吗?
这是我找到的一个相关答案,但它没有解释如果文件仍然在内存中打开,该怎么办: https://stackoverflow.com/a/76055876/23261968
尝试这样的事情:
import pandas as pd
import os
path = '{your file directory}'
file = '{your filename}'
filepath = os.path.join(path, file)
# Check if directory exists
if os.path.exists(filepath):
self.df = pandas.read_csv(filepath)