Python 3: for the list of files in the current work directory
>>> import os
>>> for file in os.listdir():
... print(file)
to include them in a list, just:
x = [f for f in os.listdir()]
If you want to have the list of a particular directory, not the directory where the terminal (or cmd) is:
>>> files = os.listdir('G:/python')
>>> for file in files:
print(file)
>>> x = [f for f in os.listdir('G:/python')]
Python 2 works differently...
>>> import os
>>> for f in os.listdir(os.getcwd):
... print f
>>> # create a list
>>> x = [f for f in os.listdir(os.getcwd())] # the current dir
The code above will print all the files in the current directory The same here:
>>> import os
>>> for f in os.listdir('.'):
... print f
>>> # create a list
>>> x = [f for f in os.listdir('.')] # the current dir
To go up in the directory tree, you got to code like this:
>>> for f in os.listdir(..):
... print f
>>> # create a list
>>> x = [f for f in os.listdir('..')] # the precedent dir
and this...
>>> for f in os.listdir('/'):
... print f
>>> # create a list
>>> x = [f for f in os.listdir('/')] # the root dir
... this will print all the files in the root directory
>>> x = [f for f in os.listdir('F:/python')] # a dir...
Comments
Post a Comment