Navigating Directories and Counting files in a directory with Python

74 Views Asked by At

I am fairly familiar with Python and coding in general but I do not have much experience with the parsing and directory navigation in Python. I have a file that contains some data that I wish to extract and I want to be able to count the number of files and directories in given directory. I have done a little research and I think the sys and os.path modules will be useful. Also do the commands for os.path vary across platforms(Yosemite vs. Linux. Windows)

1

There are 1 best solutions below

1
On BEST ANSWER

len(os.listdir('path')) will give you the total number of entries at 'path' (this includes files and directories). As far as I know, the os module is platform independent, however the strings used for paths are different for windows and unix-based environments (and maybe others, I don't know). Windows path strings should look like 'C:\\directory\\subdir\\file' because backslashes need to be escaped. I can't remember off the top of my head but I think linux path strings are just like you'd expect them to be: 'directory/subdir/file'.