使用 pathlib 遍历文件夹,我无法使用 path + value + string 打开文件

Iterate through a folder with the use of pathlib, I can´t open file with the use of path + value + string

我想在 pathlib 的帮助下遍历文件夹。 问题是,似乎我无法使用我的路径“folder”.

将值与字符串组合起来

出现以下错误:

TypeError: unsupported operand type(s) for +: 'WindowsPath' and 'str'

这是我的代码:

from pathlib import Path

#import pandas as pd
#import numpy as np

if name == 'main':

folder = Path('ASCII/')

TEST_NR = []

for ii in range(1,91):

    TEST_NR.append('Test' + str(ii))

DCT = {i:[] for i in TEST_NR}

for jj in TEST_NR:

    DCT['%s' % jj] = []

for kk in range(90):

    with open(folder / TEST_NR[kk] + '.txt') as f: ######### *ERROR* ##########

        for _ in range(17):

            next(f)

        for line in f:

            DCT[TEST_NR[kk]].append(line.strip().split(','))

我确信它非常基本,但我不知道如何处理它。

有什么想法吗?

在将其传递到 pathlib.Path 之前创建文件名变量。

for kk in range(90):
    var = TEST_NR[kk] + '.txt'
    with open(folder / var ) as f:

另一个更明确的1版本是:

for kk in range(90):
    file_path = folder / TEST_NR[kk]
    with open(file_path.with_extension('.txt')) as f:

此外,请原谅未征求意见,但在 Python 中我们通常直接遍历列表而不是使用索引。在这种情况下,您的代码将变为:

from pathlib import Path
from collections import defaultdict


if __name__ == '__main__':
    folder = Path('ASCII')

    # using a defaultdict will return an empty list when 
    # requesting an index that does not exist
    DCT = defaultdict(list)

    for test_num in range(1,91):
        test_path = Path(f'Test{test_num}')
        with open(folder / test_path.with_suffix('.txt')) as test_file:
            for _ in range(17):
                next(test_file)

            for line in test_file:
                DCT[test_path].append(line.strip().split(','))

1 显式优于隐式。 (The Zen of Python)