如何使用 os.listdir 避免 FileNotFoundError

How to avoid a FileNotFoundError with os.listdir

我正在开发一个循环,其中对指定目录中的每个 csv 进行重新采样,然后导出到一个新文件中。尽管尝试了各种文件夹并使用了确切的文件夹路径,但我还是收到了 FileNotFoundError。

# Specify folder name
serial = '015'

# Specify directory (note - '...' substitute for the full path used back to the drive letter)

root_dir = '...\CleanTemps\{}\'.format(str(serial)) 

#loop
for filename in os.listdir(root_dir):
    if filename.endswith('.csv'):

        print(filename)

        # Pull in the file
        df = pd.read_csv(filename)

这将打印该文件夹中八个 .csv 文件的列表。但是,当使用以下代码拉入文件时(作为 df 逐一修改,我收到 FileNotFoundError:


#loop
for filename in os.listdir(root_dir):
    if filename.endswith('.csv'):

        # Pull in the file
        df = pd.read_csv(filename)

您必须提供文件的完整(或相对)路径,而不仅仅是其名称,此路径基于文件的根目录,您可以使用 os.path.join 来构建它:

df = pd.read_csv(os.path.join(root_dir, file_name))

你的文件路径由root_path+你的文件名组成,你可以使用:

from pathlib import Path 

root_path = Path(root_dir)

for filename in os.listdir(root_path):
    if filename.endswith('.csv'):

        # Pull in the file
        df = pd.read_csv(root_path/filename)

或者您可以使用:

for filepath in root_path.glob("*.csv"):
    df = pd.read_csv(filepath)