Thanh Phan
Thanh Phan

Reputation: 11

Python - expected string not list

When running the code below, I got the error message saying 'TypeError: expected str, bytes or os.PathLike object, not list'

I used Spyder to debug the above error message - but I could not find the bug. Could someone please tell me how to solve this error? The code is given below

Thank you!

J1 = ['520A','520B']
J2 = ['560S','580A']

JOINTS = J1 + J2

FILES_IN = ['dynres-x-eqk.lst','dynres-y-eqk.lst','dynres-z-eqk.lst'] 
FILE_OUT = ['_Accelerations.txt']

def joint_acc(joint, file_in):
    output = []
    with open(file_in, 'rt') as f_in:
        for line in f_in:
            if 'JOINT ACCELERATIONS' in line:
                for line in f_in:
                    if line.startswith(joint):
                        while line.strip() != '':
                            output.append(line)
                            line = next(f_in)
                        break
    return ''.join(output)

with open(FILE_OUT, 'wt') as f_out:
    for Jt in JOINTS:
        for filename in FILES_IN:
            f_out.write(joint_acc(Jt, filename))
        f_out.write('\n')

Upvotes: 1

Views: 932

Answers (2)

milanbalazs
milanbalazs

Reputation: 5339

Your FILE_OUT variable is list type but the open waits for str, bytes or os.PathLike object types.

You should convert your FILE_OUT variable to a correct type.

For example to string:

FILE_OUT = "_Accelerations.txt"

Or your can access the first element of your list with 0 index (Your list has only 1 element.)

Like this:

with open(FILE_OUT[0], 'wt') as f_out:

Upvotes: 0

Daweo
Daweo

Reputation: 36838

You did:

FILE_OUT = ['_Accelerations.txt']

then:

with open(FILE_OUT, 'wt') as f_out:

So this open get list, which cause TypeError. Try replacing FILE_OUT = ['_Accelerations.txt'] with FILE_OUT = '_Accelerations.txt'

Upvotes: 6

Related Questions