为什么 try/exception 方法不适用于我的 python?
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()
这个returns
'C:/Users/..s/....csv' : this file is valid to use
但是当我执行下一个命令时
table.import_csv()
它returns
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/..s/....csv'
不确定为什么他们一开始找不到 OS 错误?
编辑:抱歉,我只是把 print 方法放在 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.")
os.path.existsreturnsTrue/False。它不会引发异常。无论文件是否存在,都会打印“此文件有效”,因为没有异常阻止它。
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()
这个returns
'C:/Users/..s/....csv' : this file is valid to use
但是当我执行下一个命令时
table.import_csv()
它returns
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/..s/....csv'
不确定为什么他们一开始找不到 OS 错误?
编辑:抱歉,我只是把 print 方法放在 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.")
os.path.existsreturnsTrue/False。它不会引发异常。无论文件是否存在,都会打印“此文件有效”,因为没有异常阻止它。