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.
 

Reading data from a file

When reading a text file, the stream of bytes enters the program input sequentially one after the other, so the file provides sequential access to data. That is, if we need to read the 10th value from the file, we must first read the previous 9.

Reading a single line of a file allows the readline() method to execute. This method is called on a file variable. Fin = open("input.txt") s = Fin.readline()
Various methods can be applied to the read string, similar to those used when reading from the keyboard (split(), map(), etc.). For example, if there are two numbers separated by a space in a line of a file, then you can count them as follows: Fin = open("input.txt") s = Fin.readline().split() # split line on spaces s = ["2007", "2021"] a, b = map(int, s)         # apply the int() method to all elements of the list s,   # that is, convert the character string to a number # a, b = int(s[0], s[1])   # this is the same as the line above # a, b = [int(x) for x in s] # same as a generator
The read() method reads the entire contents of the file and returns a string that may contain the characters '\n'. If an integer parameter is passed to the read() method, no more than the specified number of characters will be read. For example, you can read a file byte by byte using the read(1).
method.
When a file is opened, the pointer that determines the current location in the file is set to the beginning of the file and, when read, is shifted to the position following the data read. When writing, the pointer is moved to the next free position.

Write data to file

The write() method is used to write data to a file. Numeric data must be converted to a string. This can be done either with the format() method or with the str().
method
 

Multiline Files

When working with multi-line files, you need to know when the data in the file runs out. To do this, you can use the feature of the readline() methods: if the file cursor points to the end of the file, then the readline() method returns an empty string, which is perceived as a false boolean value: while True:     s = Fin.readline()     if not s: break   # if an empty string is received when reading a string,   # the loop ends with a break statement     print(s, end="")  # disable newline, because when reading a line from a file                       # newline character "\n" saved

 

Other ways to read data from multiline files
1. Immediately all the data in the list. Fin = open("input.txt") list_strings = Fin.readlines()    # read all lines at once Fin.close() for s in list_strings:     print(s, end="")
2. Using the construction with-as. In this case, the file is closed automatically after the end of the cycle. with open("input.txt") as Fin:     for s in Fin:         print(s, end="") This construct ensures that the file is closed. 


3. A way to iterate over strings in the style of the Python language (it is recommended to use this method). In this case, the file is also closed automatically. for s in open("input.txt"):     print(s, end="")

Cyrillic file

If the file contains Russian letters (any character with a code greater than 127), then you must specify the encoding when opening data = open("input.txt", "r", encoding="utf-8")