Python >> Operating Files and Folders

2022-12-25 Python

Table of Contents

This tutorial will introduce some tips and tricks about operating files and folders using python.

Python

To operate files and folders in Windows using Python, you can use the built-in os and shutil module. This module provides functions to interact with the operating system’s file system.

Here are some examples of how you can use the os module to operate on files and folders in Windows:

Make folders

  1. To create a new folder, you can use the os.makedirs() function. For example:
import os

# Create a new folder called "newfolder"
os.makedirs("C:\\newfolder")

Delete folders

To delete a folder, you can use the shutil.rmtree() function. For example:

import os

# Delete the folder "oldfolder" and all of its contents
shutil.rmtree("C:\\oldfolder")

Get file list

To list the files and folders in a directory, you can use the os.listdir() function. For example:

import os

# List the files and folders in the current directory
files_and_folders = os.listdir()

# Print the list of files and folders
print(files_and_folders)

Rename files or folders

To rename a file or folder, you can use the os.rename() function. For example:

import os

# Rename the file "oldname.txt" to "newname.txt"
os.rename("oldname.txt", "newname.txt")

# Rename the folder "oldfolder" to "newfolder"
os.rename("C:\\oldfolder", "C:\\newfolder")

Move files or folders

To move a file or folder to a different location, you can use the shutil module’s shutil.move() function. For example:

import shutil

# Move the file "myfile.txt" to the folder "C:\\newfolder"
shutil.move("myfile.txt", "C:\\newfolder")

# Move the folder "C:\\oldfolder" to the folder "C:\\newfolder"
shutil.move("C:\\oldfolder", "C:\\newfolder")

Copy files or folders

To copy a file or folder, you can use the shutil module’s shutil.copy() function. For example:

import shutil

# Copy the file "myfile.txt" to the folder "C:\\newfolder"
shutil.copy("myfile.txt", "C:\\newfolder")

# Copy the folder "C:\\oldfolder" to the folder "C:\\newfolder"
shutil.copytree("C:\\oldfolder", "C:\\newfolder\\oldfolder")

Check file or folder existence

To check if a file exists or not in Python, you can use the os module’s os.path.exists() function. This function takes a file or folder path as an argument and returns True if the path exists and False if it does not.

Here’s an example of how you can use os.path.exists() to check if a file called “myfile.txt” exists:

import os

if os.path.exists("myfile.txt"): # You can also specify folder path here
    print("File exists")
else:
    print("File does not exist")

You can also use the os module’s os.path.isfile() function to check if a path is a file. This function returns True if the path is a file and False if it is not. For example:

import os

if os.path.isfile("myfile.txt"):
    print("Path is a file")
else:
    print("Path is not a file")

Read and Write files

To read and write a file in Python, you can use the built-in open() function. This function returns a file object that you can use to read or write the file.

Here’s an example of how you can use open() to read a file called “myfile.txt”:

# Open the file in read mode
with open("myfile.txt", "r") as f:
    # Read the contents of the file
    contents = f.read()
    print(contents)

To write to a file, you can use the write() method of the file object. Here’s an example of how you can use open() to write to a file called “myfile.txt”:

# Open the file in write mode
with open("myfile.txt", "w") as f:
    # Write some text to the file
    f.write("Hello, world!")

You can also use the open() function to append to a file by using the “a” mode. Here’s an example of how you can use open() to append to a file called “myfile.txt”:

# Open the file in append mode
with open("myfile.txt", "a") as f:
    # Append some text to the file
    f.write("\nThis is additional text.")

Get path, file name, file extension

To get the file path, file name, and file extension of a file in Python, you can use the os.path module. This module provides functions for working with file paths.

Here’s an example of how you can use the os.path module to get the file path, file name, and file extension of a file called “C:\myfolder\myfile.txt”:

import os

# Get the file path
file_path = "C:\\myfolder\\myfile.txt"

# Use the os.path.dirname() function to get the directory name
dirname = os.path.dirname(file_path)
print("Directory name:", dirname)

# Use the os.path.basename() function to get the base name (i.e., the file name and extension)
basename = os.path.basename(file_path)
print("File name:", basename)

# Use the os.path.splitext() function to get the file name and extension separately
filename, extension = os.path.splitext(file_path)
print("Extension:", extension)

This will output the following:

Directory name: C:\myfolder
File name: myfile.txt
Extension: .txt

Get file size

To get the size of a file in Python, you can use the os module’s os.path.getsize() function. This function takes a file path as an argument and returns the size of the file in bytes.

Here’s an example of how you can use os.path.getsize() to get the size of a file called “myfile.txt”:

import os

# Get the size of the file in bytes
file_size = os.path.getsize("myfile.txt")

# Print the size of the file
print("File size:", file_size, "bytes")

If you want to get the size of the file in a more human-readable format, such as kilobytes or megabytes, you can divide the size by the appropriate conversion factor. For example:

import os

# Get the size of the file in bytes
file_size = os.path.getsize("myfile.txt")

# Convert the size to kilobytes
file_size_kb = file_size / 1024
print("File size:", file_size_kb, "KB")

# Convert the size to megabytes
file_size_mb = file_size / 1024 / 1024
print("File size:", file_size_mb, "MB")

Get folder size

To get the size of a folder and all of its contents (including subfolders) in Python, you can use the os module’s os.walk() function in combination with the os.path.getsize() function.

Here’s an example of how you can use these functions to get the size of a folder called “myfolder”:

import os

# Initialize a variable to store the total size
total_size = 0

# Walk through all the files and folders in the directory
for root, dirs, files in os.walk("myfolder"):
    # Add the size of each file to the total size
    for file in files:
        file_path = os.path.join(root, file)
        total_size += os.path.getsize(file_path)

# Print the total size of the folder
print("Total size:", total_size, "bytes")

This will give you the total size of the folder and all of its contents in bytes. If you want to get the size in a more human-readable format, such as kilobytes or megabytes, you can divide the size by the appropriate conversion factor. For example:

import os

# Initialize a variable to store the total size
total_size = 0

# Walk through all the files and folders in the directory
for root, dirs, files in os.walk("myfolder"):
    # Add the size of each file to the total size
    for file in files:
        file_path = os.path.join(root, file)
        total_size += os.path.getsize(file_path)

# Convert the total size to kilobytes
total_size_kb = total_size / 1024
print("Total size:", total_size_kb, "KB")

# Convert the total size to megabytes
total_size_mb = total_size / 1024 / 1024
print("Total size:", total_size_mb, "MB")

Get folder structure

To get the folder structure of a directory in Python, you can use the os module’s os.walk() function. This function generates a list of all the files and subdirectories in a directory, recursively.

Here’s an example of how you can use os.walk() to print the folder structure of a directory called “myfolder”:

import os

# Walk through all the files and folders in the directory
for root, dirs, files in os.walk("myfolder"):
    # Print the name of each file and folder
    for file in files:
        print(os.path.join(root, file))
    for dir in dirs:
        print(os.path.join(root, dir))

This will print the full paths of all the files and folders in the directory, starting from the root directory. If you only want to print the names of the files and folders (without the full paths), you can use the os.path.basename() function to get the base name (i.e., the file or folder name without the path). For example:

import os

# Walk through all the files and folders in the directory
for root, dirs, files in os.walk("myfolder"):
    # Print the name of each file
    for file in files:
        print(os.path.basename(file))
    # Print the name of each folder
    for dir in dirs:
        print(os.path.basename(dir))

Subscribe and be the FIRST reader of our latest articles

* indicates required

Contact us