Files
A file is a set of data in external memory that has a name.
There are two types of files in Python:
-
text, which contains text broken on a line; Of the special characters in text files, there can only be newline characters ("
\n
") and return to the beginning of the line ("
\r
");
-
binary, which stores any binary data without restrictions (for example, pictures, sounds, videos, etc.).
Next, we will consider working with text files.
The principle of working with a file from the program
Consists of three stages:
1. opening a file;
2. work with the file;
3. closing the file.
This principle of operation is called the
"sandwich principle"..
When opening a file, the mode of operation is indicated: reading, writing, or appending data to the end of the file. The opened file is blocked and other programs cannot access it. After working with the file, you must close it to break the connection with the program. When a file is closed, all changes made by the program in this file are written to disk. Python works with files through file variables.
The
open()
function allows
to open a file and returns a file variable that can be used to access the file.
f = open(file_name, access_mode)
,
where:
-
file_name
- name of the file to be opened
-
access_mode
- file opening mode. It can be: read, write, etc. The default mode is read (r) unless otherwise specified.
Full list of file opening modes
Mode |
Description |
r |
Read-only. |
w |
Writable only. Will create a new file if not found with the specified name. |
rb |
Read-only (binary). |
wb |
Write-only (binary). Will create a new file if not found with the specified name. |
r+ |
For reading and writing. |
rb+ |
For reading and writing (binary). |
w+ |
For reading and writing. Will create a new writable file if not found with the specified name. |
wb+ |
For reading and writing (binary). Will create a new writable file if not found with the specified name. |
a |
Opens to add new content. Will create a new writable file if not found with the specified name. |
a+ |
Opens to add new content. Will create a new file to read the entry if not found with the specified name. |
ab |
Opens to add new content (binary). Will create a new writable file if not found with the specified name. |
ab+ |
Opens to add new content (binary). Will create a new file to read the entry if not found with the specified name. |
The
close()
method allows you to
close a file.
Example
Fin = open("input.txt")
Fout = open("output.txt")
# do something with files
fout.close()
Fin.close()
If an existing file is opened for writing, its contents are destroyed. After the end of the program, all open files are closed automatically.