0

I want to read alternative of any of this 2 file xyz.csv and abc.csv, at a time one will be present:

if abc.csv not in Path8:
    pd.read_csv(Path8 + 'xyz.csv')
Martin Evans
  • 45,791
  • 17
  • 81
  • 97
  • 1
    https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists-without-exceptions – Chris May 20 '19 at 15:52

1 Answers1

0

You can use Python's os.path.isfile() function to test if your file exists before asking Pandas to open the CSV file. Pandas itself does not support such logic. For example:

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}")

os.path.join() is a safer way of constructing file paths.


An alternative approach would be to catch the FileNotFound exception that Pandas would raise if the file was not found and to then try another file. This approach would also allow you to easily extend it to give more possible filenames to try:

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)
Martin Evans
  • 45,791
  • 17
  • 81
  • 97