Denis
Denis

Reputation: 15

Open files using For-loop (Python 3)

Sorry I'm new to Python 3 and I already kept looking for an answer here in SO but I can't find the specific answer to my question rather I may not asking the right question.

I have a file named test5.txt where I have written the file names of the files that I want to open/read using Python namely, (test2.txt, test3.txt and test4.txt) these txt documents have random words on it.

Here is my code:

with open("test5.txt") as x:
    my_file = x.readlines()

for each_record in my_file:
    with open(each_record) as y:
        read_files = y.read()
        print(read_files)

But sadly I'm getting error: "OSError: [Errno 22] Invalid argument: 'test2.txt\n'"

Upvotes: 0

Views: 818

Answers (2)

Roelant
Roelant

Reputation: 5119

Would suggest to use rstrip rather than strip - better to be safe and explicit.

for each_record in my_file:
    with open(each_record.rstrip()) as y:
        read_files = y.read()
        print(read_files)

But this should also work and is maybe more beautiful, using the str.splitlines method - see this post here.

 with open("test5.txt") as x:
    list_of_files = x.read().splitlines()

Upvotes: 2

digitake
digitake

Reputation: 856

It seems like each_record contains a newline \n character. You can try to strip the filename string before open it as a file.

with open("test5.txt") as x:
    my_file = x.readlines()

for each_record in my_file:
    with open(each_record.strip()) as y:
        read_files = y.read()
        print(read_files)

Upvotes: 0

Related Questions