pythonfor-looppathlibunsupportedoperation

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


I would like to iterate through a folder with the help of pathlib. The problem is, it seems, that I can´t combine a value with a string with the use of my path "folder".

The following error appears:

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

This is my code:

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(','))

I am sure its very basic but I don´t know how to handle it.

Any ideas?


Solution

  • Create the filename variable before passing it into pathlib.Path.
    i.e.

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