List the content of a folder using python [duplicate] - python

This question already has answers here:
How can I list the contents of a directory in Python?
(8 answers)
Closed 4 years ago.
Is it possible to output the contents of a folder in python ?
If, say you had a function and you would pass the folder path to its argument?
What would be the simplest way for a beginner to take?
By "simplest" I mean, without using any modules.
Note
Google usually leads me to stackoverflow. Plus I am not looking for generic answers. I am looking for insight based on experience and wit, which I can only find here.

You could use os.listdir() to look at the contents of a directory. It takes the path as an argument, for example:
import os
directory = os.listdir('/')
for filename in directory:
print(filename)
prints this for me:
bin
home
usr
sbin
proc
tmp
dev
media
srv
etc
lib64
mnt
boot
run
var
sys
lib
opt
root
.dockerenv
run_dir

How about listdir? Let's try like this way-
import os
def ShowDirectory:
return os.listdir("folder/path/goes/here")
ShowDirectory()

With function.
def ListFolder(folder):
import os
files = os.listdir(folder)
print(*files,sep="\n")

Please use google first next time...it seems you are looking for this:
How can I list the contents of a directory in Python?
The accepted answer there:
import os
os.listdir("path") # returns list

Related

How to create a function that prints the name of all files in a directory and calls itself recursively on any subdirectories?

Beginner learning python here. The longer version of the question is:
Write a python program (create your function) that prints the names of all the files
available in a directory (path of the directory is taken as input), and if the directory contain any directory (or more directories) then it calls itself recursively on all the directories.
The question suggests using os.path.join() if needed as well.
I have a brief idea of what the question is asking, but none of the ideas I came up with worked. All the answers I found on here were for different languages, too. I would appreciate some pointers as the very least...
I solved the question! I implemented both recursion and os.walk that was suggested by #take-study.
def dirlist(file):
import os
path = [x[0] for x in os.walk(file)]
for i in os.listdir(file):
print(i)
for k in path[1:]:
print("now printing files of subdirectory {}:".format(k))
dirlist(k)
file = input("Enter file path: ")
dirlist(file)
And it worked! Thank you for your help, everyone.
use os.walk to get all files under the root_path,the result is a tuple include dir and nomal files

Make a List for sub directories path [duplicate]

This question already has answers here:
Getting a list of all subdirectories in the current directory
(34 answers)
Closed 7 years ago.
I have a directory and I need to make a path list for the sub directories.
For example my main directory is
C:\A
which contains four different sub directories : A1,A2,A3,A4
I need a list like this:
Path_List = ["C:\A\A1","C:\A\A2","C:\A\A3","C:\A\A4"]
Cheers
import os
base_dir = os.getcwd()
sub_dirs = [os.path.join(base_dir, d) for d in os.listdir(base_dir)]
You could (and should, i think) use os module, wich is easy to use and provides a lot of stuff to deal with paths.
I wont say anymore, because your question is vague and shows no effort on searching. You are welcome!!
sub_dirs = os.listdir(os.getcwd()) ## Assuming you start the script in C:/A
path_list = []
for i in sub_dirs:
path_list.append(os.path.join(os.getcwd(),i))
Dirty and fast.

Copy directory contents into a directory with python [duplicate]

This question already has answers here:
How do I copy an entire directory of files into an existing directory using Python?
(15 answers)
Closed 4 years ago.
I have a directory /a/b/c that has files and subdirectories.
I need to copy the /a/b/c/* in the /x/y/z directory. What python methods can I use?
I tried shutil.copytree("a/b/c", "/x/y/z"), but python tries to create /x/y/z and raises an error "Directory exists".
I found this code working which is part of the standard library:
from distutils.dir_util import copy_tree
# copy subdirectory example
from_directory = "/a/b/c"
to_directory = "/x/y/z"
copy_tree(from_directory, to_directory)
Reference:
Python 2: https://docs.python.org/2/distutils/apiref.html#distutils.dir_util.copy_tree
Python 3: https://docs.python.org/3/distutils/apiref.html#distutils.dir_util.copy_tree
You can also use glob2 to recursively collect all paths (using ** subfolders wildcard) and then use shutil.copyfile, saving the paths
glob2 link: https://code.activestate.com/pypm/glob2/
from subprocess import call
def cp_dir(source, target):
call(['cp', '-a', source, target]) # Linux
cp_dir('/a/b/c/', '/x/y/z/')
It works for me. Basically, it executes shell command cp.
The python libs are obsolete with this function. I've done one that works correctly:
import os
import shutil
def copydirectorykut(src, dst):
os.chdir(dst)
list=os.listdir(src)
nom= src+'.txt'
fitx= open(nom, 'w')
for item in list:
fitx.write("%s\n" % item)
fitx.close()
f = open(nom,'r')
for line in f.readlines():
if "." in line:
shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
else:
if not os.path.exists(dst+'/'+line[:-1]):
os.makedirs(dst+'/'+line[:-1])
copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
f.close()
os.remove(nom)
os.chdir('..')

What is the Python equivalent of Perl's FindBin? [duplicate]

This question already has answers here:
How do you properly determine the current script directory?
(16 answers)
Closed 5 years ago.
In Perl, the FindBin module is used to locate the directory of the original script. What's the canonical way to get this directory in Python?
Some of the options I've seen:
os.path.dirname(os.path.realpath(sys.argv[0]))
os.path.abspath(os.path.dirname(sys.argv[0]))
os.path.abspath(os.path.dirname(__file__))
You can try this:
import os
bindir = os.path.abspath(os.path.dirname(__file__))
That will give you the absolute path of the current file's directory.
I don't use Python very often so I do not know if there is package like FindBin but
import os
import sys
bindir = os.path.abspath(os.path.dirname(sys.argv[0]))
should work.
To update on the previous answers, with Python 3.4+, you can now do:
import pathlib
bindir = pathlib.Path(__file__).resolve().parent
Which will give you the same, except you'll get a Path object that is way more nice to work with.

How to create new folder? [duplicate]

This question already has answers here:
How can I safely create a directory (possibly including intermediate directories)?
(28 answers)
Closed 8 years ago.
I want to put output information of my program to a folder. if given folder does not exist, then the program should create a new folder with folder name as given in the program. Is this possible? If yes, please let me know how.
Suppose I have given folder path like "C:\Program Files\alex" and alex folder doesn't exist then program should create alex folder and should put output information in the alex folder.
You can create a folder with os.makedirs()
and use os.path.exists() to see if it already exists:
newpath = r'C:\Program Files\arbitrary'
if not os.path.exists(newpath):
os.makedirs(newpath)
If you're trying to make an installer: Windows Installer does a lot of work for you.
Have you tried os.mkdir?
You might also try this little code snippet:
mypath = ...
if not os.path.isdir(mypath):
os.makedirs(mypath)
makedirs creates multiple levels of directories, if needed.
You probably want os.makedirs as it will create intermediate directories as well, if needed.
import os
#dir is not keyword
def makemydir(whatever):
try:
os.makedirs(whatever)
except OSError:
pass
# let exception propagate if we just can't
# cd into the specified directory
os.chdir(whatever)

Categories