Last Updated:

How to Write and Read to text files in Python

Modern programming has a wide range of languages, which are constantly updated with new products. Each of them has its own advantages and disadvantages. The most popular in recent years is Python. It has a large functionality that allows you to work with files, saving the state of the program on the hard disk of the device.

How to Write and Read to text files in Python

Рython: working with files and requirements for them


If you explain in simple words, then a file is a certain area of the disk, which implies the storage of data for a long period. Before you do any work with it, you need to open it. After all the changes are made, it is closed to free up the resources associated with it. All operations in this programming language occur according to the following algorithm:

  • opening;
  • read or write;
  • closing.

Careful observance of this order guarantees you to perform all the necessary functions. The classification of files in Python occurs in two main groups:

  • text;
  • Binary.

The first option is based on data that is readable to a person. They have a sequence of characters placed in editors, notepads and other types of files. Storing simple texts is indicated by the format (.txt) and complex by (.rtf)

The second option is encoded information in the form of 1 and 0. Most often it is a sequence of bits. The format for their storage is indicated by the abbreviation .bin.

How to read files in Python


In order to start performing certain actions with the file, you need to use a function called "open". The syntax for this process is as follows:

f = open(file_name, access_mode)

In this line, you must specify the name of the file to open, as well as the mode in which to open. It can be for writing, reading, or other activities. The "read-only" option implies a standard mode for opening files. This programming language automatically browses the folder where the script is located. If an error occurs, you will receive a notification.

You may get an incorrect path if you do not define the string as the original one. The main reasons for this may be the special characters displayed. As soon as the opening occurs, most often a row with the data variable is read.

The next step of readline python work with files - open file will be to print the information and shut down the file descriptor. This is a prerequisite in order to restrict access to your files of other programs.

Such actions save memory and prevent the appearance of strange bugs in the system. You can specify whether to read the string only once or play the file in parts. The second option is mainly used for processing large volumes.

The main ability to read a file in parts is considered to be the use of a loop. Initially, the task is to master the ability to read one line at a time. Subsequently, kilobytes will become available at a time. This function can be used against any object in a given programming language.

Binary files are read by changing the way the file is accessed. This point is especially important when there is a need to work with PDF files.

Work and record files in Python


To write something in the file in Python you need to enter "w" and "wb". Using these modes in a file that already exists will make the edits without warning. For viewing, it is recommended to use the OS module. Also, to work with Python, writing to the file and reading from the file line by line occurs based on the change in mode and specified method in the file descriptor.

Using the writelines tool will allow you to change a whole list of lines at once, the handle writes information to disk one by one.

The recording algorithm is performed as follows:

initially open the file to perform the action:

 f = open(‘text.txt’, ‘w’)

then using the write method

for index in l:
... f.write(index + ‘\n’)

The presence of numbers means that the method returns the recorded characters.

when all actions are certified, enter the close method


as a result of the performed actions we get the following:

 f = open('text.txt', 'r')
l = [line.strip() for line in f]
['0-1′, '10', '21', '32', '43', '54', '65', '76', '87', '98', '109', '1110', '1211', '1312', '1413', '1514', '1615', '1716', '1817', '1918']

This is the simplest and most popular option used to work with simple texts used as an entry in the Python file For more complex cases, you can use tools such as json or pickle. With their help, more complex structures are preserved.

Instruction with with


Options for working with data and approaches to solve the task, another approach has been developed. A construct called "with open python 3" greatly simplifies exception handling. Its main functionality is to encapsulate the initial operations, and in addition to the tasks of cleaning and closing.

The advantage of this method is the absence of the need to use the word "close". The file will be closed automatically.

Here's how it's all going to come out in reality:

with open('example.txt') as f:
# working with a file

Most programmers note that working with this language is quite simple. The main requirements for employees may be the study of the main processes. The activity of the functionality is carried out on clearly defined algorithms.