All the files in your hard drive with os.walk()

How can I see all the files in the hard drive?

With os.walk() you can litteraly take a walk into all your files. In this example, the code will create three txt files with the files, some ordered and some with full path, to give an example of what you can do.
The os.walk() function returns the root, the list of dirs and the list of files of a dir. That is why the code below unpacked this data in three variables root, dirs and files.

Running this program you will have three files:

  1. lista_file.txt, with all the files names as the program finds them (unordered)
  2. lista_file_ordinata.txt, all files ordered
  3. percorso.txt, the complete path of files

"""We are going to save a txt file with all the files in your directory.
We will use the function walk()

"""

import os

# two lists to contain the names and the complete path
listafile = []
percorso = []
# here we create the txt file with names without order
with open("lista_file.txt", "w", encoding='utf-8') as testo:
    for root, dirs, files in os.walk("D:\\"):
        for file in files:
            listafile.append(file) # create the list with names
            percorso.append(root + "\\" + file) # create the list with paths
            testo.write(file + "\n") # write the txt file unordered
# order the list of names
listafile.sort()
# prints the number of files in the dir
print("N. of files", len(listafile))

# we write the files with the ordered file names
with open("lista_file_ordinata.txt", "w", encoding="utf-8") as testo_ordinato:
    for file in listafile:
        testo_ordinato.write(file + "\n") # write the ordered file

# we write the file with the whole path of the files
with open("percorso.txt", "w", encoding="utf-8") as file_percorso:
    for file in percorso:
        file_percorso.write(file + "\n")# write all the paths

# we open the three files we just created
os.system("lista_file.txt")
os.system("lista_file_ordinata.txt")
os.system("percorso.txt")

Next time we could make a program that allows us to open the files using tkinter and os.system.

Utilities

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.