0

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?

2 Answers 2

1

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:
1
  • Works like a charm! :) Thanks!
    – Nils
    Aug 23, 2018 at 8:11
0

Another, more explicit1 version would be:

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

Also, please pardon the unasked advice, but in Python we usually iterate directly through lists rather than using indices. In this case, your code would become:

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

I

1 Explicit is better than implicit. (The Zen of Python)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.