-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

user7090
  • 83
  • 1
  • 6

2 Answers2

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()
James
  • 32,991
  • 4
  • 47
  • 70
  • 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 Jul 20 '20 at 20:25
  • @user7090 Sounds like you might need to open the file as binary format (`'rb'` instead of `'r'`). – alani Jul 20 '20 at 20:31
  • @alaniwi Is it possible to open the file in read format instead of reading in binary format – user7090 Jul 20 '20 at 20:37
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:
        ...
Barmar
  • 741,623
  • 53
  • 500
  • 612