Mr. Johnny Doe
Mr. Johnny Doe

Reputation: 99

reading files from a folder using os module

for a pattern recognition application, I want to read and operate on jpeg files from another folder using the os module.

I tried to use str(file) and file.encode('latin-1') but they both give me errors

I tried :

allLines = []

path = 'results/'
fileList = os.listdir(path)
for file in fileList:
   file = open(os.path.join('results/'+ str(file.encode('latin-1'))), 'r')
   allLines.append(file.read())
print(allLines)

but I get an error saying: No such file or directory "results/b'thefilename"

when I expect a list with the desired file names that are accessible

Upvotes: 1

Views: 1542

Answers (1)

Querenker
Querenker

Reputation: 2365

If you can use Python 3.4 or newer, you can use the pathlib module to handle the paths.

from pathlib import Path

all_lines = []
path = Path('results/')
for file in path.iterdir():
    with file.open() as f:
        all_lines.append(f.read())
print(all_lines)

By using the with statement, you don't have to close the file descriptor by hand (what is currently missing), even if an exception is raised at some point.

Upvotes: 1

Related Questions