|
| 1 | +import os |
| 2 | + |
| 3 | +# print the current directory |
| 4 | +print("The current directory:", os.getcwd()) |
| 5 | + |
| 6 | +# make an empty directory (folder) |
| 7 | +os.mkdir("folder") |
| 8 | +# running mkdir again with the same name raises FileExistsError, run this instead: |
| 9 | +# if not os.path.isdir("folder"): |
| 10 | +# os.mkdir("folder") |
| 11 | +# changing the current directory to 'folder' |
| 12 | +os.chdir("folder") |
| 13 | +# printing the current directory now |
| 14 | +print("The current directory changing the directory to folder:", os.getcwd()) |
| 15 | + |
| 16 | +# go back a directory |
| 17 | +os.chdir("..") |
| 18 | + |
| 19 | +# make several nested directories |
| 20 | +os.makedirs("nested1/nested2/nested3") |
| 21 | + |
| 22 | +# create a new text file |
| 23 | +text_file = open("text.txt", "w") |
| 24 | +# write to this file some text |
| 25 | +text_file.write("This is a text file") |
| 26 | + |
| 27 | +# rename text.txt to renamed-text.txt |
| 28 | +os.rename("text.txt", "renamed-text.txt") |
| 29 | + |
| 30 | +# replace (move) this file to another directory |
| 31 | +os.replace("renamed-text.txt", "folder/renamed-text.txt") |
| 32 | + |
| 33 | +# print all files and folders in the current directory |
| 34 | +print("All folders & files:", os.listdir()) |
| 35 | + |
| 36 | +# print all files & folders recursively |
| 37 | +for dirpath, dirnames, filenames in os.walk("."): |
| 38 | + # iterate over directories |
| 39 | + for dirname in dirnames: |
| 40 | + print("Directory:", os.path.join(dirpath, dirname)) |
| 41 | + # iterate over files |
| 42 | + for filename in filenames: |
| 43 | + print("File:", os.path.join(dirpath, filename)) |
| 44 | +# delete that file |
| 45 | +os.remove("folder/renamed-text.txt") |
| 46 | +# remove the folder |
| 47 | +os.rmdir("folder") |
| 48 | + |
| 49 | +# remove nested folders |
| 50 | +os.removedirs("nested1/nested2/nested3") |
| 51 | + |
| 52 | +open("text.txt", "w").write("This is a text file") |
| 53 | + |
| 54 | +# print some stats about the file |
| 55 | +print(os.stat("text.txt")) |
| 56 | + |
| 57 | +# get the file size for example |
| 58 | +print("File size:", os.stat("text.txt").st_size) |
0 commit comments