如何读取“abc.csv”,如果没有,则使用pandas读取“xyz.csv”?

2024-09-25 00:26:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我想读取这两个文件中的任意一个xyz.csvabc.csv,一次会出现一个:

if abc.csv not in Path8:
    pd.read_csv(Path8 + 'xyz.csv')

Tags: 文件csvinreadifnotpdabc
1条回答
网友
1楼 · 发布于 2024-09-25 00:26:52

在请求Pandas打开CSV文件之前,可以使用Python的^{}函数测试文件是否存在。熊猫本身并不支持这种逻辑。例如:

import pandas as pd
import os.path

Path8 = '/my/path'
file1 = os.path.join(Path8, 'abc.csv')
file2 = os.path.join(Path8, 'xyz.csv')

if os.path.isfile(file1):
    print(f"Opening {file1}")
    df = pd.read_csv(file1)
    print(df)
elif os.path.isfile(file2):
    print(f"Opening {file2}")
    df = pd.read_csv(file2)
    print(df)
else:
    print(f"abc.csv and xyz.csv not found in {Path8}")

^{}是构建文件路径的一种更安全的方法


另一种方法是捕获Pandas在找不到文件时引发的FileNotFound异常,然后尝试另一个文件。这种方法还允许您轻松地扩展它,以提供更多可能的文件名:

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)

相关问题 更多 >