Working with files in Python

Introduction

In this article you will learn how to organize file handling in Python 3.

Create a file files.py and copy the code from the examples into it.

You can run the file with the command

python3 files.py

Banner image
Basics
Create
open(): Open
close(): Close
with: Context manager
read(): reading a file
readline(): line-by-line reading
Clear the file
Copy the file
Write to a file
Append to the file
Banner image
More complex topics
seek(0): move to the beginning of the file
Write json to a file
Delete the first few lines of a file
Writing program output to a file
Detect file encodings
Read a file from another directory
Find a string
Delete a specific line
Delete everything between tags
Remove the file extension
glob
glob basics
Search by pattern
Search in multiple directories
Search in subdirectories
Search for hidden files
shutil
Copy options
copyfile
copy
move
os
getcwd() and chdir()
listdir(): Directory contents
Create a directory
Delete a directory
rename(): Rename a file
os.stat(): file information
os.walk(): walk directories
os.environ()
os.path():
join()
dirname()
split(), splitext()
exists(), isdir, isfile
pathlib
cwd()
stat(): Metadata
exists(): Check existence

Article author: Andrei Olegovich