Table of Contents:

Master Python from scratch: a free course on creating Telegram bots, web parsers, and websites under the guidance of an expert from "Sbera"
Learn moreWorking with files is a fundamental skill for programmers. Files are used to store service logs, key data, calculation results—anything that is important to preserve. Python offers convenient built-in functions with clear syntax for performing these tasks. In this article, we will discuss how to create, copy, open, and read files, as well as how to write new information to them.
Contents
- Python allows you to interact with various file types, allowing you to process data in a wide variety of formats. First of all, these are text documents that can contain simple information in the form of strings. Such files typically have the extensions .txt or .csv.
In addition, Python supports working with JSON files, which is especially convenient for exchanging data between applications and storing structured information. It is also possible to process XML files, which are widely used to represent data in a hierarchical form.
Another important type of file is binary, which can contain images, audio, or video. In this case, specialized libraries are used, such as PIL for working with images or the wave library for processing sound files.
Don't forget about Excel formats, where Python can be useful for analyzing and processing tabular data using libraries such as pandas.
Thus, Python provides flexible tools for working with a variety of files, making it a universal programming language for solving many data processing problems.
- How to open a file
- Working with files, including reading and writing them, is an important aspect of programming. The process of reading allows you to extract information from a file, while writing ensures that data is saved to the file. These operations can be performed using various methods, depending on the programming language and the file format.
When reading a file, a program accesses its contents, which allows it to obtain the desired data for further processing. In most cases, before you can work with a file, you need to open it, which can be done in either read or write mode. After completing your operations, the file should be closed to avoid memory leaks and other problems.
Writing data to a file usually involves creating or updating its contents. Depending on the requirements, a program can write data incrementally or load it entirely. It is also important to keep in mind that when overwriting a file, previous information may be lost unless specified otherwise.
Therefore, effective file management requires attention to detail and an understanding of the different modes of working with them.
- Cursor Control
- How to Close a File
- File management in an operating system is an important aspect of working with a computer. This process includes creating, editing, moving and deleting files, as well as organizing their storage.
For starters, creating a new file is usually done through the context menu, accessible by right-clicking in the desired folder. Selecting the appropriate file type allows you to quickly launch the desired program. Editing files is typically done using specialized software appropriate to the document format.
Moving files can be done by simply dragging them from one folder to another or using copy and paste commands. Deleting, in turn, is done by selecting a file and pressing the Delete key or through the context menu.
Organizing files involves creating folders to structure them. This helps maintain order and makes it easier to find the information you need. It is also worth paying attention to the use of shortcuts, which can speed up access to frequently used documents.
Don't forget the importance of regularly backing up your data to avoid loss of information in the event of a system crash or file corruption.
File types available for processing in Python
There are two main categories of files in Python:
- Text files are documents containing information that is easily perceived by humans. These files include formats with extensions such as .txt, .csv, .log, .ini, .json, .xml, and others.
- Binary files are data encoded as a sequence of bytes. This category includes various documents such as .jpg, .png, .gif, .docx, .mp4, .exe, .dat, and many others. Their processing usually requires specialized programs. For example, Photoshop is often used for image editing, and Final Cut Pro for working with video.
Next, we will look at functions in Python that can process both text and binary files. However, keep in mind that if you open an image, instead of the usual vacation photo, you will see a set of characters. This will be a binary sequence representing the image encoding.

Read also:
How to learn Python on your own and without financial costs: a step-by-step guide.
How to open a file
Before you start editing a file, It needs to be opened. In Python, the open() function is used for this purpose. It takes two arguments: the file name and the mode in which it will be opened, and returns an object representing the file. In general, this function looks like this:
In it:
- file_name — this can be either a relative path (for example, data/input.txt) or an absolute path (for example, C:\Users\User\Documents\my_file.txt) to the file.
- mode — this is the parameter that specifies how you are going to open the file. For example, you can set it to read-only mode to prevent accidental deletion of information.
- encoding_type — this is the parameter that determines the encoding of text files. In the default configuration, Python uses the system values: on Windows it is CP1251, and on Linux it is UTF-8. When working with Cyrillic, it is recommended to explicitly specify UTF-8 to avoid possible problems with displaying characters on different platforms.

Read also:
Functions in Python: A Complete Guide
Methods of Interacting with File Data
Let's look at the key modes of interacting with files in Python, which can be specified as a parameter when calling the open() function:
- ‘r’ is the mode in which the file is opened for reading. It is important to note that the file itself must already exist, otherwise a FileNotFoundError error will occur.
- ‘w’ mode allows you to open a file for writing. If the file already exists, Python will delete all its data, and if it does not exist, a new file will be created.
- ‘a’ allows you to append information to the end of an existing file. If the file does not exist, Python will create a new file with the specified name.
- ‘x’ — generates a file using the name given in the function arguments.
- ‘b’ allows you to interact with binary files, such as images. This flag must be used in conjunction with one of the previously mentioned open modes: ‘rb’, ‘wb’, ‘ab’, or ‘xb’.
- The ‘+’ mode is a general-purpose mode that allows you to perform both reading and writing operations simultaneously. It must be used in conjunction with one of the previously mentioned open modes: ‘r+’, ‘w+’, ‘a+’ or ‘x+’.

File Handling: Reading and Writing Data
Once a file is open, you can begin to interact with its data. Python has a number of convenient functions that will help with this process. Let's look at how to use them correctly.
Data can be extracted from a file using various functions:
The read() method allows you to extract the entire contents of a file and save it in a single line. This approach is suitable for working with small files. If you have precise information about the number of characters to read, you can specify this value as an argument. For example, calling file.read(100) will mean that only the first 100 characters of the file will be read.
The readline() function allows you to read the contents of a file line by line. In doing so, it stores the newline character (\n) after each line. Even if there is an empty line in the file, the function also takes it into account.
The readlines() function allows you to extract lines from a file and save them as a list, where each line is represented by a separate element. This method is ideal for cases where you need to process lines individually.
The for line in file loop allows you to extract information from a file line by line and process each individual line. This method is especially useful when working with large files, since it does not load the entire file into RAM at once.
Using Python, you can append information to a file, for example, writing to a log file. To do this, you need to open the file using the open() function in write mode, and then use one of the available functions:
write() is a function designed to write a line to a file. If you need to split the text into multiple lines, you must use the line feed character (\n):
The main characteristic of the write() function is that it is designed exclusively for working with strings. If you need to write numeric values to a file, you must first convert this data to string format.
The writelines() function is designed to write a list of lines to a file. As an input parameter, it accepts a list containing strings as its elements.

Read also:
Lists in Python: concept and methods of working with them
Lists are one of the fundamental data types in Python, allowing you to store sequences of values. These structures can contain elements of different types, such as numbers, strings, or even other lists. Due to their flexibility and ease of use, lists have become an important tool in programming.
To create a list, you use square brackets to place elements separated by commas. For example, you could define a list containing different fruits: `fruits = [‘apple’, ‘banana’, ‘pear’]`.
Working with lists involves many operations. These include adding new elements, removing existing ones, and changing values by index. For example, to add an element to the end of a list, use the `append()` method, and to remove an element, use the `remove()` method, which removes the first occurrence of the specified value.
Indexing allows you to access list elements by their position, starting from zero. Thus, the first element of a list can be retrieved by specifying the index 0, and the last element can be retrieved using negative indices.
Lists also support slicing, which allows you to retrieve subsets of elements. For example, `fruits[1:3]` will return the elements with indices 1 and 2. This makes working with data more convenient and efficient.
Furthermore, lists have many built-in methods, such as `sort()`, which sorts the elements, or `reverse()`, which reverses their order. These tools greatly simplify data manipulation.
In conclusion, lists in Python are a powerful and versatile tool that gives developers the ability to organize and process data with ease and flexibility.
While the print() function in Python is most often used to display information in the console, it can also be used to write data to a file using the file parameter. This method is convenient because it automatically adds a line break character.
Cursor Management
In some cases, it is necessary to extract information from a specific part of a file, for example, from its central area. Python provides functions that allow you to manage the cursor in a file, which makes it possible to move it to the desired position and continue working with data from this point. Let's look at the functions available for this task:
The tell() function allows you to find out where exactly the cursor is located in an open file. It returns a value indicating the number of bytes counted from the beginning of the file to the current cursor position. Keep in mind that in text files, this number does not always match the number of characters that have been read or written, since characters may occupy a different number of bytes depending on the encoding used.
The seek(offset, whence=0) function is used to change the position of the cursor in a file. When calling this function, you must specify two parameters: the offset in bytes to move the cursor to, and the relative offset value (whence). By default, the second parameter is set to 0, which means the offset from the beginning of the file, but other options exist:
- 1 - relative to the current cursor position;
- 2 - from the end of the file.
For example, to move the cursor 10 bytes from the beginning of the file, you can use the following method:
How to close a file
When you are finished working with a file, be sure to close it. If you ignore this step, there is a risk of data loss, and other applications on your device will not be able to open this file.
In the Python programming language, the close() method is used to finish working with files.
To simplify working with files, you can use the with open(…) as construct, which not only automatically closes files when finished but also makes the code neater and easier to read. Here's an example of how to use this construct:
Efficient File Handling in the Operating System
Python not only supports reading and writing files, but also creates, deletes, renames, copies, and moves them. The os, shutil, and pathlib modules are used to perform these tasks.
A list of key capabilities for working with files in Python:
- os.path.exists(‘file_name’) — checks if a file with the given name exists.
- os.remove(‘file_name’) — deletes the specified file.
- os.rename(‘old_name’, ‘new_name’) — this command changes the name of the file.
- shutil.move(‘old_folder/file.txt’, ‘new_folder/file.txt’) — moves a file from one location to another.
- The os.listdir(‘folder’) command allows you to get a list of files and directories located in the specified folder.
Consider the following example, in which we will develop a program that can create a file, then copy it, and finally delete the original file.

Read also:
Introduction to IDLE for Python: From the Start to Writing Your First Program
What to Remember
- Python provides the ability to work with both text and binary files, and all the necessary functions for this activity can be found in the standard library.
- Before making any changes to a file, you must open it using the open() function. As a parameter, you must specify the mode in which you are going to work with the document. This mode determines what operations can be performed with the file after it is opened.
- When you are finished working with the document, it is extremely important to use the close() function to close the file. Otherwise, there is a risk that your changes will not be saved.
- Python modules such as os, shutil, and pathlib provide a number of functions designed to interact with the file system. With their help, you can not only create files and directories, but also perform operations such as copying, deleting, and changing the names of these objects.
Want to learn more exciting things about coding? Join our Telegram channel!
Read also:
- Lists in Python: Definition and How to Use Them
Lists are one of the key data types in Python, allowing you to store collections of elements in an organized manner. They can contain elements of various types, including numbers, strings, and even other lists. Working with lists in Python is quite simple, and they have a rich set of methods for manipulating data.
A list can be created using square brackets, within which elements are separated by commas. For example, you can create a list containing numbers: `[1, 2, 3, 4]`, or a list of strings: `[«apple», «banana», «cherry»]`. You can also initialize an empty list with `[]`.
List elements are accessed through their indices, starting from zero. Thus, to get the first element of the list, you must specify index 0. For example, for the list `fruits = [«apple», «banana», «cherry»]`, the expression `fruits[0]` returns «apple».
Lists in Python are dynamic, which means that their size can change while the program is running. Elements can be added, removed, or modified. To add an element to the end of a list, use the append() method, for example, fruits.append(orange) will add orange to the end of the list. If you want to insert an element at a specific position, you can use the insert() method, specifying the index and the value.
Elements can be removed using the remove() method, which removes the first occurrence of the specified value, or using pop(), which removes the element at the specified index and returns it. If no index is specified, pop() will remove the last element.
Lists support various operations, such as concatenation and repetition. Concatenation is performed using the + operator, and repetition is performed using *. For example, `list1 + list2` will concatenate two lists, and `list * 3` will create a new list consisting of three copies of the original.
Furthermore, lists can be easily processed using loops and list comprehensions, allowing you to create new lists based on existing ones. This makes them a powerful tool for working with data in Python.
In conclusion, lists are a versatile and flexible means of storing and managing data in Python, providing many opportunities for effective programming.
- Test your skills: can you distinguish between the principles of Zen of Python and the philosophical ideas of Lao Tzu?
- Basic data types in Python for beginners: what they are and how to interact with them.
