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

Benyamin Jafari
  • 27,880
  • 26
  • 135
  • 150
Denis
  • 15
  • 2
  • Do you check this [post](https://stackoverflow.com/questions/25584124/oserror-errno-22-invalid-argument-when-use-open-in-python)? – Benyamin Jafari Oct 06 '18 at 06:19

2 Answers2

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()
Roelant
  • 4,508
  • 1
  • 32
  • 62
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)
digitake
  • 846
  • 7
  • 16
  • 2
    It worked! thank you man digitake! I have been working for 4 hours to figure this out :) .strip() worked like a charm! – Denis Oct 06 '18 at 06:57