File Operations
Create a File
Section titled “Create a File”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.
open('test.txt', 'w').close()Output:
C:\Users\username>python create_file.pyIn 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.
Rename a File
Section titled “Rename a File”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:
os.rename(src, dst)Example:
import os
os.rename('test.txt', 'new_test.txt')Output:
C:\Users\username>python rename_file.pyIn 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.
Delete a File
Section titled “Delete a 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:
os.remove(path)Example:
import os
os.remove('new_test.txt')Output:
C:\Users\username>python delete_file.pyIn 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.
Create a Directory
Section titled “Create a Directory”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:
os.mkdir(path)Example:
import os
os.mkdir('test')Output:
C:\Users\username>python create_directory.pyIn 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.
Rename a Directory
Section titled “Rename a Directory”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:
os.rename(src, dst)Example:
import os
os.rename('test', 'new_test')Output:
C:\Users\username>python rename_directory.pyIn 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.
Delete a Directory
Section titled “Delete a 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:
os.rmdir(path)Example:
import os
os.rmdir('new_test')Output:
C:\Users\username>python delete_directory.pyIn 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.
Move a File
Section titled “Move a File”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:
shutil.move(src, dst)Example:
import shutil
shutil.move('test.txt', 'test')Output:
C:\Users\username>python move_file.pyIn 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.
Move a Directory
Section titled “Move a Directory”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:
shutil.move(src, dst)Example:
import shutil
shutil.move('test', 'new_test')Output:
C:\Users\username>python move_directory.pyIn 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.
Copy a File
Section titled “Copy a File”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:
shutil.copy(src, dst)Example:
import shutil
shutil.copy('test.txt', 'test')Output:
C:\Users\username>python copy_file.pyIn 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.
Copy a Directory
Section titled “Copy a Directory”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:
shutil.copytree(src, dst)Example:
import shutil
shutil.copytree('test', 'new_test')Output:
C:\Users\username>python copy_directory.pyIn 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.
List Files and Directories
Section titled “List Files and Directories”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:
os.listdir(path)Example:
import os
print(os.listdir())Output:
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.
Check if a File Exists
Section titled “Check if a File Exists”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:
os.path.exists(path)Example:
import os
print(os.path.exists('test.txt'))Output:
C:\Users\username>python check_if_file_exists.py
TrueIn 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.
Check if a Directory Exists
Section titled “Check if a Directory Exists”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:
os.path.exists(path)Example:
import os
print(os.path.exists('test'))Output:
C:\Users\username>python check_if_directory_exists.py
TrueIn 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.
Get the Current Working Directory
Section titled “Get the Current Working Directory”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:
os.getcwd()Example:
import os
print(os.getcwd())Output:
C:\Users\username>python get_current_working_directory.py
C:\Users\usernameIn the above example, we are using the getcwd() function to get the current working directory. The getcwd() function takes no argument.
Change the Current Working Directory
Section titled “Change the Current Working Directory”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:
os.chdir(path)Example:
import os
os.chdir('test')Output:
C:\Users\username>python change_current_working_directory.pyIn 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.
Get the Size of a File
Section titled “Get the Size of a File”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:
os.path.getsize(path)Example:
import os
print(os.path.getsize('test.txt'))Output:
C:\Users\username>python get_file_size.py
0In 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.
Get the Size of a Directory
Section titled “Get the Size of a Directory”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:
shutil.disk_usage(path)Example:
import shutil
print(shutil.disk_usage('test'))Output:
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.
What the mode string actually decides
Section titled “What the mode string actually decides”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.
flowchart TD
O["open(path, mode)"] --> M{"mode"}
M -->|"r"| R["must exist
read only, cursor at 0"]
M -->|"w"| W["created or TRUNCATED
write only, cursor at 0"]
M -->|"a"| A["created if missing
every write goes to the END"]
M -->|"x"| X["must NOT exist
else FileExistsError"]
M -->|"r+"| RP["must exist, read and write
cursor at 0, OVERWRITES in place"]
M -->|"w+"| WP["read and write
but still truncates first"]
Measured, starting from a file containing SEED and writing a single X:
| mode | file afterwards | note |
|---|---|---|
w | X | old contents gone before you wrote anything |
a | SEEDX | appended |
x | SEED | FileExistsError, nothing written |
r+ | XEED | overwrote one character in place |
w+ | X | + does not prevent truncation |
Opening is not writing: the buffer
Section titled “Opening is not writing: the buffer”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 closeWrites 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 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) # TrueSee it move
Section titled “See it move”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.
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).
Text mode rewrites your newlines
Section titled “Text mode rewrites your newlines”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 bytesFour 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.
Check yourself
Section titled “Check yourself”-
A file contains SEED. You open it with mode 'r+' and write 'X'. What does it contain?
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.
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.
-
Which mode raises FileExistsError when the file is already there?
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.
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.
-
On Windows you write the 4-character string a\nb\n in text mode. How many bytes land on disk?
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.
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.
-
You call f.read() on an open handle, then call f.read() again. What does the second call return?
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.
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.
Conclusion
Section titled “Conclusion”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.
Try it: File Operations Exercises
Section titled “Try it: File Operations Exercises”Exercise 1 – Check File Exists
Section titled “Exercise 1 – Check File Exists”Exercise 2 – Read Lines
Section titled “Exercise 2 – Read Lines”Exercise 3 – Delete a File
Section titled “Exercise 3 – Delete a File”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading