0

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'"

1
  • Do you check this post? Commented Oct 6, 2018 at 6:19

2 Answers 2

2

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()
Sign up to request clarification or add additional context in comments.

Comments

0

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)

1 Comment

It worked! thank you man digitake! I have been working for 4 hours to figure this out :) .strip() worked like a charm!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.