Is there a way to read the names of multiple .txt files from a single folder? I right now am only able to read the contents of the files.
import glob
import errno
path = 'C:/Users/rabhi/Desktop/NLP/aclImdb/test/neg/*.txt'
files = glob.glob(path)
for name in files:
try:
with open(name) as f:
for line in f:
print(line.split())
except IOError as exc:
if exc.errno != errno.EISDIR:
raise
You can use os.walk() for this:
import os
def main():
for dirName, subDirList, fileList in os.walk('path'):
for subDir in subDirList:
for file in fileList:
#Do something with file
main()
This recursively goes through your files in a given directory. To ignore sub-directories you can try something like this:
import os
def main():
for dirName, subDirList, fileList in os.walk('path'):
for file in fileList:
#Do something with file
main()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.