python 分割字符串并使用 .find 获取最后三个字母以确定文件类型

python slice a string and use .find to get last three letters to determine the type of file

我想问的是如何更正我的 if 语句,基本上我有一个名为 'fileName' 的文件附件,我正在尝试从该文件中获取最后 3 个字母以确定该文件类型在我的配置中(csv、txt)。

valid_filename = 我的配置文件(csv、txt)

def load_file():
    try:
        # get file from read email and assign a directory path (attachments/file)
        for fileName in os.listdir(config['files']['folder_path']):
            # validate the file extension per config
            # if valid_filename:  else send email failure
            valid_filename = config['valid_files']['valid']
            if fileName[-3:].find(valid_filename):
                file_path = os.path.join(config['files']['folder_path'], fileName)
                # open file path and read it as csv file using csv.reader
                with open(file_path, "r") as csv_file:
                    csvReader = csv.reader(csv_file, delimiter=',')
                    first_row = True

让我知道我是否可以澄清任何更好的事情

find() 方法 returns -1 如果找不到您正在搜索的字符串。要检查该元素是否存在于字符串中,请检查是否 find returns -1.

试试 pathlib,例如

假设配置文件的格式为:

[valid_files]
valid = .csv, .txt
[files]
forder_path = .
# other imports
import pathlib

def load_file():
    valid_suffixes = [e.strip() for e in config['valid_files']['valid'].split(",")]
    folder_path = config['files']['folder_path']
    for fileName in os.listdir(folder_path):
        if pathlib.Path(filename).suffix in valid_suffixes:
            file_path = os.path.join(folder_path, fileName)
            with open(file_path, "r") as csv_file:
                ...