-1

I am trying to open the file using a path instead of file name I used glob.glob option to go and search in the path for an input file. Now I got struck with opening that. Any help would be appreciated.

import glob
a = (glob.glob("*/file.txt"))
with open (a, 'r') as f:

Trying to read the file.txt and I am getting error in line3. Any help would be appreciated.

Error: TypeError: expacted str, bytes or os.PathLike object, not list

0

2 Answers 2

1

glob.glob returns a list of file paths. You will need to access one of the paths in the list, or iterate over them.

import glob

a = glob.glob("*/file.txt")
with open(a[0], 'r') as f:
    text= f.read()
Sign up to request clarification or add additional context in comments.

3 Comments

It is still giving me error saying : (result, consumed) = sel._buffer_decode(data, self.error, final) UnicodeDecodeError: 'utf - 8' code can't decode byte 0x8b in position 1: invalid start byte.
@user7090 Sounds like you might need to open the file as binary format ('rb' instead of 'r').
@alaniwi Is it possible to open the file in read format instead of reading in binary format
0

glob.glob() returns a list. You need to loop through it, opening each file.

import glob

for filename in glob.glob("*/file.txt"):
    with open(filename, "r") as f:
        ...

10 Comments

I am facing the same error as mentioned in the above comment
That's completely unrelated. It's not a plain text file.
Or you need to specify the encoding
Will it read the data in the file.txt if we use glob.glob() option
How you get the filename has nothing to do with how you read the file.
|

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.