Creating files in Python: a complete guide
Working with files is one of the main tasks in Python programming. In this guide, we will take a detailed look at how to create, read, write, and manage files in Python.
Basics of working with files
Python uses the built-in open() function with various opening modes to create new files. The basic structure of working with files is as follows:
# Creating a new text file
with open('новый_файл.txt ', 'mode') as f:
pass # In this example, the file will be empty, since we are not writing anything to it.
Using the with construction guarantees that the file is automatically closed after completion, even if an error occurs.
File management modes
Python provides several modes for working with files:
mode
| Description | |
|---|---|
'r' |
Opening a file for reading. The file must exist |
'w' |
Opening a file for writing. If the file does not exist, it will be created. If the file exists, its contents will be overwritten |
'a' |
Opening a file to add (append) to the end of the file. If the file does not exist, it will be created |
'x' |
Opening a file for exclusive creation. If a file with the specified name already exists, the operation will fail |
'b' |
An additional mode that indicates that the file is opened in binary mode. For example, 'wb' for writing in binary mode |
'+' |
An additional mode that allows you to open a file for both reading and writing. For example, 'r+' or 'w+' |
Practical examples of working with files
Reading the file ('r')
with open('file.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
Writing to a file ('w')
with open('file.txt', 'w', encoding='utf-8') as f:
f.write('Hello, World!')
Appending to the end of the file ('a')
with open('file.txt', 'a', encoding='utf-8') as f:
f.write('\nNew line appended.')
Exclusive file creation ('x')
try:
with open('new_file.txt', 'x', encoding='utf-8') as f:
f.write('Content for the new file.')
print('The file has been created successfully!')
except FileExistsError:
print('The file already exists!')
Working with binary files ('rb', 'wb')
# Reading a binary file
with open('image.jpg', 'rb') as f:
image_data = f.read()
# Writing a binary file
with open('copy_image.jpg', 'wb') as f:
f.write(image_data)
Simultaneous reading and writing ('r+', 'w+')
# r+ mode - the file must exist
with open('file.txt', 'r+', encoding='utf-8') as f:
content = f.read()
f.write('Additional text')
# w+ mode - the file is created if it does not exist
with open('new_file.txt', 'w+', encoding='utf-8') as f:
f.write('Initial content')
f.seek(0) # Move the pointer to the beginning of the file
content = f.read()
File management using the shutil module
Copying files
import shutil
# Copying
the shutil.copy file('исходный_файл.txt ', 'новый_файл.txt ')
# Copying a file while preserving the metadata
shutil.copy2('исходный_файл.txt ', 'новый_файл.txt ')
# Copying the entire directory tree
shutil.copytree('source folder', 'destination folder')
Moving and renaming files
import os
import shutil
# Renaming the file
os.rename('старое_имя.txt ', 'новое_имя.txt ')
# Moving the file
shutil.move('исходный_файл.txt ', 'целевая_папка/новое_имя.txt ')
Deleting files and checking for existence
Deleting files
import os
# Deleting a file
try:
os.remove('файл_для_удаления.txt ')
print('File deleted successfully')
except FileNotFoundError:
print('File not found')
except PermissionError:
print('Insufficient permissions to delete the file')
Checking the existence of a file
import os.path
# Checking the existence of the file
if os.path.exists('файл.txt '):
print('The file exists')
else:
print('The file does not exist')
# Checking if the path is a file
if os.path.isfile('файл.txt '):
print('This is the file')
# Checking if the path is a directory
if os.path.isdir('folder'):
print('This is the directory')
File search
File search by extension or name
import glob
import os
# Search for files with the ".txt"
extension txt_files = glob.glob('*.txt')
print('Found txt files:', txt_files)
# Search for files in subfolders
all_txt_files = glob.glob('**/*.txt', recursive=True)
# Search for files using os.listdir()
files_in_directory = [f for f in os.listdir('.') if f.endswith('.txt')]
Getting information about a file
import os.path
import time
# Getting the file size in bytes
size = os.path.getsize('файл.txt ')
print(f'File size: {size} bytes')
# Getting the time of the last access to
the atime = os.path file.getatime('файл.txt ')
print(f'Last access: {time.ctime(atime)}')
# Getting the time of the last file change
mtime = os.path.getmtime('файл.txt ')
print(f'Last modified: {time.ctime(mtime)}')
# Getting the absolute path to the file
abs_path = os.path.abspath('файл.txt ')
print(f' Absolute path: {abs_path}')
Error handling when working with files
When working with files, it is important to provide for possible error handling.:
import os
def safe_file_operation(filename):
try:
with open(filename, 'r', encoding='utf-8') as f:
content = f.read()
return content
except FileNotFoundError:
print(f'File {filename} not found')
except PermissionError:
print(f'Insufficient permissions to read the {filename} file')
except UnicodeDecodeError:
print(f' Encoding error when reading the {filename} file')
except Exception as e:
print(f' Unexpected error: {e}')
return None
Best practices for working with files
- Always use the context manager
withto automatically close files - Specify the encoding when working with text files (usually
encoding='utf-8') - Handle exceptions to prevent program crashes
- Check the existence of files before reading operations
- Use the appropriate modules (
shutilfor copying,osfor basic operations)
Working with files in Python provides powerful data management capabilities. Proper use of file opening modes and exception handling will help you create reliable and effective programs.