Python Directory and Files Management
import os
current_dir = os.getcwd()
print(current_dir)import os
os.chdir("C:/Projects")
print(os.getcwd())import os
items = os.listdir(".")
print(items)Last updated
import os
current_dir = os.getcwd()
print(current_dir)import os
os.chdir("C:/Projects")
print(os.getcwd())import os
items = os.listdir(".")
print(items)Last updated
import os
os.mkdir("new_folder")
os.makedirs("parent/child/grandchild")import os
print(os.path.exists("data.txt")) # True or False
print(os.path.isfile("data.txt")) # Checks file
print(os.path.isdir("new_folder")) # Checks directorywith open("sample.txt", "w") as file:
file.write("Hello, Python File System")with open("sample.txt", "r") as file:
content = file.read()
print(content)import os
os.rename("sample.txt", "renamed.txt")
os.remove("renamed.txt")import shutil
shutil.copy("source.txt", "backup.txt")
shutil.move("backup.txt", "archive/backup.txt")from pathlib import Path
file_path = Path("example.txt")
file_path.write_text("Using pathlib module")
print(file_path.read_text())
print(file_path.exists())
print(file_path.parent)