0

I have a following problem. My .py script is saved in "C:\Users\vojtam\Desktop\my_script". I would like to get a list of all files that are saved in "C:\Users\vojtam\Desktop\my_folder". I know that I can use:

os.chdir("C:\Users\vojtam\Desktop\my_folder")
list_of_files = os.listdir()

But is it possible without the command os.chdir? Thanks a lot!

tituszban
  • 4,797
  • 2
  • 19
  • 30
vojtam
  • 1,157
  • 9
  • 34

2 Answers2

2

help is often helpful in such case, if you do in python terminal help(os.listdir) it will inform you

listdir(path=None)
    Return a list containing the names of the files in the directory.

    path can be specified as either str, bytes, or a path-like object.  If path is bytes,
      the filenames returned will also be bytes; in all other circumstances
      the filenames returned will be str.
    If path is None, uses the path='.'.

and so on, therfore in this case just do

import os
list_of_files = os.listdir("C:\Users\vojtam\Desktop\my_folder")
Daweo
  • 31,313
  • 3
  • 12
  • 25
1

You can use glob:

import glob

list_of_files = glob.glob("C:\Users\vojtam\Desktop\my_folder\*")
enzo
  • 9,861
  • 3
  • 15
  • 38