How to read all files and also the filenames? I am using MAC so is there any there a different way to give path on MAC in Python?
Asked
Active
Viewed 1,898 times
1
-
1Macs are just POSIX systems, same as Linux. There is no different way of handling paths for OS X. What have you tried yourself so far? Have you seen `os.listdir()` yet? – Martijn Pieters Dec 07 '13 at 23:44
-
hm.. i'm pretty sure you can google this quite easily.. – aIKid Dec 07 '13 at 23:45
-
import glob path = '/folder/' files=glob.glob(path) cnt=0 for htmlfile in files: f=open(htmlfile).read() print cnt f.readlines() cnt=cnt+1 f.close() – user2793286 Dec 07 '13 at 23:51
-
I have given relative path – user2793286 Dec 07 '13 at 23:51
1 Answers
1
Maybe something like this? Or os.listdir() is simpler if you don't need recursion.
Even on Windows, Python abstracts away the differences between operating systems if you use it well.
#!/usr/local/cpython-3.3/bin/python
import os
def main():
for root, dirs, files in os.walk('/home/dstromberg/src/outside-questions'):
for directory in dirs:
print('directory', os.path.join(root, directory))
for file_ in files:
print('file', os.path.join(root, file_))
main()
See http://docs.python.org/3/library/os.html for more info.

dstromberg
- 6,954
- 1
- 26
- 27