0

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.

  • `os` is default module i.e you don't need to install it manually – A l w a y s S u n n y Nov 18 '18 at 15:30
  • What is a default module? One you don't have to import or one you don't have to download. Because if it's a default module as `math` is, then it's not this I am looking for. –  Nov 18 '18 at 15:32

4 Answers4

0

How about listdir? Let's try like this way-

import os

def ShowDirectory: 
   return os.listdir("folder/path/goes/here")

ShowDirectory()
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
0

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
Teemu
  • 286
  • 1
  • 2
  • 10
0

With function.

def ListFolder(folder):
    import os
    files = os.listdir(folder)
    print(*files,sep="\n")
Hayat
  • 1,539
  • 4
  • 18
  • 32
-2

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
NemoMeMeliorEst
  • 513
  • 4
  • 10
  • 1
    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. –  Nov 18 '18 at 15:26
  • which has been already answered in above link i gave you...;) Goodluck – NemoMeMeliorEst Nov 18 '18 at 18:58