import pandas as pd
import os.path
Path8 = '/my/path'
files = [os.path.join(Path8, filename) for filename in ["abc.csv", "xyz.csv"]]
for csv_file in files:
try:
df = pd.read_csv(csv_file)
break
except FileNotFoundError:
df = None
if df is None:
print(f"{', '.join(files)} - not found in {Path8}")
else:
print(f"Opened {csv_file}")
print(df)
在请求Pandas打开CSV文件之前,可以使用Python的^{} 函数测试文件是否存在。熊猫本身并不支持这种逻辑。例如:
^{} 是构建文件路径的一种更安全的方法
另一种方法是捕获Pandas在找不到文件时引发的
FileNotFound
异常,然后尝试另一个文件。这种方法还允许您轻松地扩展它,以提供更多可能的文件名:相关问题 更多 >
编程相关推荐