Skip to content

File Operations

We are creating a file named test.txt using os module. The os module provides functions for interacting with the operating system. The os module comes under Python’s standard utility modules. We are using the os module to create a file in the current directory.

create_file.py
open('test.txt', 'w').close()

Output:

command
C:\Users\username>python create_file.py

In the above example, we are using the open() function to create a file. The open() function takes two arguments. The first argument is the name of the file and the second argument is the mode. The mode is used to specify the purpose of opening the file. The w mode is used to open the file for writing. The open() function returns a file object. We are using the close() method to close the file object.

We are renaming the file test.txt to new_test.txt using the os module. The os module provides functions for interacting with the operating system. The os module comes under Python’s standard utility modules. We are using the os module to rename a file in the current directory.

Syntax:

rename_file.py
os.rename(src, dst)

Example:

rename_file.py
import os
 
os.rename('test.txt', 'new_test.txt')

Output:

command
C:\Users\username>python rename_file.py

In the above example, we are using the rename() function to rename a file. The rename() function takes two arguments. The first argument is the old name of the file and the second argument is the new name of the file.

We are deleting the file new_test.txt using the os module. The os module provides functions for interacting with the operating system. The os module comes under Python’s standard utility modules. We are using the os module to delete a file in the current directory.

Syntax:

delete_file.py
os.remove(path)

Example:

delete_file.py
import os
 
os.remove('new_test.txt')

Output:

command
C:\Users\username>python delete_file.py

In the above example, we are using the remove() function to delete a file. The remove() function takes one argument. The argument is the name of the file to be deleted.

We are creating a directory named test using the os module. The os module provides functions for interacting with the operating system. The os module comes under Python’s standard utility modules. We are using the os module to create a directory in the current directory.

Syntax:

create_directory.py
os.mkdir(path)

Example:

create_directory.py
import os
 
os.mkdir('test')

Output:

command
C:\Users\username>python create_directory.py

In the above example, we are using the mkdir() function to create a directory. The mkdir() function takes one argument. The argument is the name of the directory to be created.

We are renaming the directory test to new_test using the os module. The os module provides functions for interacting with the operating system. The os module comes under Python’s standard utility modules. We are using the os module to rename a directory in the current directory.

Syntax:

rename_directory.py
os.rename(src, dst)

Example:

rename_directory.py
import os
 
os.rename('test', 'new_test')

Output:

command
C:\Users\username>python rename_directory.py

In the above example, we are using the rename() function to rename a directory. The rename() function takes two arguments. The first argument is the old name of the directory and the second argument is the new name of the directory.

We are deleting the directory new_test using the os module. The os module provides functions for interacting with the operating system. The os module comes under Python’s standard utility modules. We are using the os module to delete a directory in the current directory.

Syntax:

delete_directory.py
os.rmdir(path)

Example:

delete_directory.py
import os
 
os.rmdir('new_test')

Output:

command
C:\Users\username>python delete_directory.py

In the above example, we are using the rmdir() function to delete a directory. The rmdir() function takes one argument. The argument is the name of the directory to be deleted.

We are moving the file test.txt to the directory test using the shutil module. The shutil module provides functions for copying and moving files and directories. The shutil module comes under Python’s standard utility modules. We are using the shutil module to move a file in the current directory.

Syntax:

move_file.py
shutil.move(src, dst)

Example:

move_file.py
import shutil
 
shutil.move('test.txt', 'test')

Output:

command
C:\Users\username>python move_file.py

In the above example, we are using the move() function to move a file. The move() function takes two arguments. The first argument is the name of the file to be moved and the second argument is the name of the directory to which the file is to be moved.

We are moving the directory test to the directory new_test using the shutil module. The shutil module provides functions for copying and moving files and directories. The shutil module comes under Python’s standard utility modules. We are using the shutil module to move a directory in the current directory.

Syntax:

move_directory.py
shutil.move(src, dst)

Example:

move_directory.py
import shutil
 
shutil.move('test', 'new_test')

Output:

command
C:\Users\username>python move_directory.py

In the above example, we are using the move() function to move a directory. The move() function takes two arguments. The first argument is the name of the directory to be moved and the second argument is the name of the directory to which the directory is to be moved.

We are copying the file test.txt to the directory test using the shutil module. The shutil module provides functions for copying and moving files and directories. The shutil module comes under Python’s standard utility modules. We are using the shutil module to copy a file in the current directory.

Syntax:

copy_file.py
shutil.copy(src, dst)

Example:

copy_file.py
import shutil
 
shutil.copy('test.txt', 'test')

Output:

command
C:\Users\username>python copy_file.py

In the above example, we are using the copy() function to copy a file. The copy() function takes two arguments. The first argument is the name of the file to be copied and the second argument is the name of the directory to which the file is to be copied.

We are copying the directory test to the directory new_test using the shutil module. The shutil module provides functions for copying and moving files and directories. The shutil module comes under Python’s standard utility modules. We are using the shutil module to copy a directory in the current directory.

Syntax:

copy_directory.py
shutil.copytree(src, dst)

Example:

copy_directory.py
import shutil
 
shutil.copytree('test', 'new_test')

Output:

command
C:\Users\username>python copy_directory.py

In the above example, we are using the copytree() function to copy a directory. The copytree() function takes two arguments. The first argument is the name of the directory to be copied and the second argument is the name of the directory to which the directory is to be copied.

We are listing the files and directories in the current directory using the os module. The os module provides functions for interacting with the operating system. The os module comes under Python’s standard utility modules. We are using the os module to list the files and directories in the current directory.

Syntax:

list_files_and_directories.py
os.listdir(path)

Example:

list_files_and_directories.py
import os
 
print(os.listdir())

Output:

command
C:\Users\username>python list_files_and_directories.py
['append.py', 'create_directory.py', 'create_file.py', 'delete_directory.py', 'delete_file.py', 'File Operations.md', 'File%20Operations.md', 'move_directory.py', 'move_file.py', 'rename_directory.py', 'rename_file.py']

In the above example, we are using the listdir() function to list the files and directories in the current directory. The listdir() function takes one argument. The argument is the name of the directory whose files and directories are to be listed. If no argument is passed to the listdir() function, then it lists the files and directories in the current directory.

We are checking if the file test.txt exists in the current directory using the os module. The os module provides functions for interacting with the operating system. The os module comes under Python’s standard utility modules. We are using the os module to check if a file exists in the current directory.

Syntax:

check_if_file_exists.py
os.path.exists(path)

Example:

check_if_file_exists.py
import os
 
print(os.path.exists('test.txt'))

Output:

command
C:\Users\username>python check_if_file_exists.py
True

In the above example, we are using the exists() function to check if a file exists. The exists() function takes one argument. The argument is the name of the file whose existence is to be checked.

We are checking if the directory test exists in the current directory using the os module. The os module provides functions for interacting with the operating system. The os module comes under Python’s standard utility modules. We are using the os module to check if a directory exists in the current directory.

Syntax:

check_if_directory_exists.py
os.path.exists(path)

Example:

check_if_directory_exists.py
import os
 
print(os.path.exists('test'))

Output:

command
C:\Users\username>python check_if_directory_exists.py
True

In the above example, we are using the exists() function to check if a directory exists. The exists() function takes one argument. The argument is the name of the directory whose existence is to be checked.

We are getting the current working directory using the os module. The os module provides functions for interacting with the operating system. The os module comes under Python’s standard utility modules. We are using the os module to get the current working directory.

Syntax:

get_current_working_directory.py
os.getcwd()

Example:

get_current_working_directory.py
import os
 
print(os.getcwd())

Output:

command
C:\Users\username>python get_current_working_directory.py
C:\Users\username

In the above example, we are using the getcwd() function to get the current working directory. The getcwd() function takes no argument.

We are changing the current working directory to the directory test using the os module. The os module provides functions for interacting with the operating system. The os module comes under Python’s standard utility modules. We are using the os module to change the current working directory.

Syntax:

change_current_working_directory.py
os.chdir(path)

Example:

change_current_working_directory.py
import os
 
os.chdir('test')

Output:

command
C:\Users\username>python change_current_working_directory.py

In the above example, we are using the chdir() function to change the current working directory. The chdir() function takes one argument. The argument is the name of the directory to which the current working directory is to be changed.

We are getting the size of the file test.txt using the os module. The os module provides functions for interacting with the operating system. The os module comes under Python’s standard utility modules. We are using the os module to get the size of a file.

Syntax:

get_file_size.py
os.path.getsize(path)

Example:

get_file_size.py
import os
 
print(os.path.getsize('test.txt'))

Output:

command
C:\Users\username>python get_file_size.py
0

In the above example, we are using the getsize() function to get the size of a file. The getsize() function takes one argument. The argument is the name of the file whose size is to be obtained.

We are getting the size of the directory test using the shutil module. The shutil module provides functions for copying and moving files and directories. The shutil module comes under Python’s standard utility modules. We are using the shutil module to get the size of a directory.

Syntax:

get_directory_size.py
shutil.disk_usage(path)

Example:

get_directory_size.py
import shutil
 
print(shutil.disk_usage('test'))

Output:

command
C:\Users\username>python get_directory_size.py
usage(total=97676207104, used=97676207104, free=0)

In the above example, we are using the disk_usage() function to get the size of a directory. The disk_usage() function takes one argument. The argument is the name of the directory whose size is to be obtained.

The mode you pass to open() settles three separate questions at once: may the file be missing, is existing content destroyed, and where does the cursor start. Choosing the wrong letter is how data disappears.

diagram Diagram mermaid

Measured, starting from a file containing SEED and writing a single X:

modefile afterwardsnote
wXold contents gone before you wrote anything
aSEEDXappended
xSEEDFileExistsError, nothing written
r+XEEDoverwrote one character in place
w+X+ does not prevent truncation
buffering.py
import os
 
f = open("demo.txt", "w")
f.write("buffered, not yet on disk")
print(os.path.getsize("demo.txt"))    # 0    <- nothing on disk yet
f.close()
print(os.path.getsize("demo.txt"))    # 25   <- flushed on close

Writes land in a buffer and reach the disk when the buffer fills, when you call flush(), or when the file is closed. A crash before that point loses the data — and a script that never closes its files can leave them empty. with closes for you even if an exception is raised, which is the entire reason to prefer it:

with_block.py
with open("demo.txt", "w") as g:
    g.write("hello")
    print(os.path.getsize("demo.txt"))    # 0
print(os.path.getsize("demo.txt"))        # 5
print(g.closed)                           # True

A file handle is a cursor over bytes. Every read moves it forward; nothing rewinds it for you. Step through the operations and watch where the cursor lands — and why the second read() comes back empty.

sketch The file cursor p5.js
Reads advance the cursor and never rewind it. A second read() returns an empty string because the cursor is already at EOF.
cursor.py
with open("demo.txt") as f:          # contains "one\ntwo\nthree\n"
    print(f.tell())                  # 0
    print(f.read(3))                 # 'one'
    print(f.tell())                  # 3
    print(f.read())                  # '\ntwo\nthree\n'
    print(f.read())                  # ''      <- cursor is at EOF, file is NOT re-read
    f.seek(0)
    print(f.read(3))                 # 'one'

An empty string from read() means end of file, not an empty file. Code that reads a handle twice and finds nothing the second time is almost always missing a seek(0).

newlines.py
with open("demo.txt", "w") as f:
    f.write("a\nb\n")
print(open("demo.txt", "rb").read())     # b'a\r\nb\r\n'  -> 6 bytes on Windows
 
with open("demo.txt", "wb") as f:
    f.write(b"a\nb\n")
print(open("demo.txt", "rb").read())     # b'a\nb\n'      -> 4 bytes
 
with open("demo.txt", "w", newline="") as f:
    f.write("a\nb\n")                    # translation off -> 4 bytes

Four characters became six bytes. In text mode on Windows, \n is translated to \r\n on write and back on read, so you rarely notice — until a byte count, a hash, or a file sent to another platform disagrees. For any non-text payload, open in binary.

pch.quizTag pch.quizDefaultTitle
  1. A file contains SEED. You open it with mode 'r+' and write 'X'. What does it contain?

    pch.quizShowAnswer

    B — XEED — r+ positions the cursor at 0 and overwrites bytes in place rather than truncating. The X replaces the S and the rest survives, giving XEED.

  2. Which mode raises FileExistsError when the file is already there?

    pch.quizShowAnswer

    C — x — x is exclusive creation: it succeeds only if the file does not exist, which is how you avoid silently destroying data the way w would.

  3. On Windows you write the 4-character string a\nb\n in text mode. How many bytes land on disk?

    pch.quizShowAnswer

    B — 6, because each newline escape is translated to carriage-return plus newline — Text mode translates a newline to the platform line ending on write. Both newlines become two bytes each, giving 6. Open in binary, or pass newline='', to stop it.

  4. You call f.read() on an open handle, then call f.read() again. What does the second call return?

    pch.quizShowAnswer

    B — an empty string, because the cursor is at end of file — Reading advances the cursor and nothing rewinds it. The second read starts at EOF and returns ''. Call f.seek(0) first to read the file again.

In this tutorial, we learned how to perform file operations in Python. We learned how to create, rename, delete, and move files and directories. We also learned how to list files and directories, check if a file or directory exists, get the current working directory, change the current working directory, and get the size of a file or directory. Now you can perform file operations in Python. For more information, visit the official documentation of the os module and the official documentation of the shutil module. For more tutorials, visit our Python Central Hub.


pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading