Gwen Lee
Gwen Lee

Reputation: 49

Why try/exception method is not working on my python?

import os.path
from os import path
import pandas as pd

class ImportFiles:
    def __init__(self, pathname, file):
        self.pathname = pathname
        self.file = file

    def check(self):
        try:
            os.path.exists(self.pathname+'/'+self.file)
            print(f"'{self.pathname}/{self.file}': this file is valid to use")
        except OSError: 

          
    def import_csv(self):
        df = pd.read_csv(f"{self.pathname}/{self.file}")
        return df

if __name__ == "__main__":
    table= ImportFiles("C:/Users/..s", "....csv")
    table.check()

This returns

'C:/Users/..s/....csv' : this file is valid to use

But when I execute the next command

table.import_csv()

It returns

FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/..s/....csv'

Not sure why they couldn't find OS error at first?

Edit: Sorry, I simply put print method after except OSError

print(f"Operating system raised an error: check if the file {self.file} exsits or the name is correct. Check your path that contains this file.")

Upvotes: 0

Views: 58

Answers (1)

tdelaney
tdelaney

Reputation: 77357

os.path.exists returns True/False. It does not raise an exception. "this file is valid to use" will print regardless of whether the file exists because no exception stopped it.

Upvotes: 3

Related Questions