To find out which directory in python you are currently in, use the getcwd() method. Cwd is for current working directory in python. This returns the path of the current python directory as a string in Python. To get it as a bytes object, we use the method getcwdb().
The copy2() method in Python is used to copy the content of the source file to the destination file or directory. This method is identical to shutil. copy() method also preserving the file's metadata.
Use the os. listdir('path') function to get the list of all files of a directory. This function returns the names of the files and directories present in the directory.
import os
os.listdir("path") # returns list
One way:
import os
os.listdir("/home/username/www/")
Another way:
glob.glob("/home/username/www/*")
Examples found here.
The glob.glob
method above will not list hidden files.
Since I originally answered this question years ago, pathlib has been added to Python. My preferred way to list a directory now usually involves the iterdir
method on Path
objects:
from pathlib import Path
print(*Path("/home/username/www/").iterdir(), sep="\n")
os.walk
can be used if you need recursion:
import os
start_path = '.' # current directory
for path,dirs,files in os.walk(start_path):
for filename in files:
print os.path.join(path,filename)
glob.glob
or os.listdir
will do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With