How do I open all files in a folder in python? I need to open all files in a folder, so I can index the files for language processing.
Asked
Active
Viewed 578 times
0
-
Does this answer your question? [How do I list all files of a directory?](https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory) – sev Jun 05 '21 at 09:41
4 Answers
0
Here you have an example. here is what it does:
- os.listdir('yourBasebasePath') returns a list of files in your directory
- with open(os.path.join(os.getcwd(), filename), 'r') is opening the current file as readonly (you will not be able to write inside)
import os
for filename in os.listdir('yourBasebasePath'):
with open(os.path.join(os.getcwd(), filename), 'r') as f:
# do your stuff

Alex Spitz
- 85
- 7
0
I would recommend looking at the pathlib
library https://docs.python.org/3/library/pathlib.html
you could do something like:
from pathlib import Path
folder = Path('<folder to index>')
# get all the files in the folder
files = folder.glob('**/*.csv') # assuming the files are csv
for file in files:
with open(file, 'r') as f:
print(f.readlines())

sev
- 1,500
- 17
- 45
0
you can use os.walk for listing all the files having in your folder. you can refer os.walk documentation
import os
folderpath = r'folderpath'
for root, dirs, files in os.walk(folderpath, topdown=False):
for name in files:
print(os.path.join(root, name))
for name in dirs:
print(os.path.join(root, name))

Nevetha
- 11
- 5