Wyświetlanie listy plików i folderów w python

Jak wyświetlić pliki i foldery w python?

# the list of files and folders
import os
theList = os.listdir()
print(theList)

# the list of files in current folder
import os
filenames = next(os.walk(os.getcwd()))[2]
print(filenames)

# the list of files with given extension
import glob
txtfiles = []
for file in glob.glob("*.txt"):
    txtfiles.append(file)
print(txtfiles)

# how to save the list of files in current folder
import os
filenames = next(os.walk(os.getcwd()))[2]
print(filenames)
f = open("theList.txt", "w")
for file in filenames:
    f.write(file)
    f.write('\n')
f.close()

Jak stworzyć lub usunąć folder w python?

# create folder
import os
if not os.path.exists("myfolder"):
    os.mkdir("myfolder")
else:
    print("Folder is created already")

# delete folder if exists and empty
import os
if os.path.exists("myfolder"):
    os.rmdir("myfolder")
else:
    print("Folder doesn't exist")
Scroll to Top