The high-level Python 3 programming language provides users with a variety of useful tools for interacting with text files. The built-in methods of the platform allow you not only to create documents for storing string information, but also to read data from them, as well as to write, delete, and manipulate their contents in any way.
Creating, opening and closing files
Working with any text file in Python starts with a call to a special function open, which takes the path to the object on your computer and the processing mode as parameters. You can specify the path to the document as an absolute path (the address of the location on the PC hard disk) or as a relative path (coordinates relative to the project folder). When choosing the required mode of file processing you should take into account its purpose (“w” for writing, “r” for reading data). The following example shows a simple interaction with a text document.
file = open("test.txt", "w") file.write("hello world") file.close()
As you can see, the open function takes the relative path of the file and opens it for writing. If there is no .txt document with the same name and extension in the source code folder, the open method creates it on its own and then opens the file in the required way. After performing all necessary actions with the file variable, which refers to a real file, you should close it manually in order to avoid loss of information. The close method performs this task if you call it using the access operator (point). Performing the exact same actions, but without having to close the file manually, is possible thanks to the operator with as. To do this you need to put the open method right after the with keyword, and put a variable that will be referring to the file after the as statement. Below is an example of opening a document with as.
with open("test.txt", "w") as file: file.write("hello world")
Both examples of small programs show how to work with test.txt, which is generated in the directory with the source code. The data writing is selected as the processing mode for it. After that, the “hello world” string is written into it using the write method. The code ends in both cases by closing the text file test.txt using the close method or automatically.
To quickly write information to a text file, just open it in a Python program and use the write function with a variable referencing the document. In Python, writing to the file line by line is done by writing the desired line followed by a line feed character ‘n’. Let’s look at an example of writing a list item by item. Each item will be written on a new line:
lines = ["first", "second", "third"] with open(r "D:test.txt", "w") as file: for line in lines: file.write(line + 'n')
The above example of a small program shows the creation of a small array lines, which contains three string elements: “first”, “second”, and “third”. The function open and the operator with as are used to open the text file test.txt in the root directory of hard drive D. In the loop we loop through all list items and write them using the write command. To make each entry a new line, we add a line feed character. We can also use the function writelines. If we pass a list as its parameter, it will write the elements one after the other on one line. But we can do the following: we pass the generator as a parameter as follows.
lines = ["first", "second", "third"] with open(r "D:test.txt", "w") as file: file.writelines("%sn" % line for line in lines)
This example differs from the previous one in that it calls a writelines method that takes a generator as an argument. It uses “n” to separate elements of a sequence, so each word in the document will be on a separate line.
Read line by line
Reading the content of a text file line by line in Python is very easy, because the for loop does a great job. But first, you will have to open the document, just like in the previous case, using open and with as. This time, however, we should specify a different mode for the file, choosing “r” for read access to the data.
with open(r "D:test.txt", "r") as file: for line in file: print(line)
This example shows opening of file test.txt which already contains a small array of lines written earlier. Line-by-line reading of information from the file is done in a for loop. Each iteration prints the information from a new line with the function print. All items are displayed on the screen line by line as they were placed in test.txt earlier.
Number of lines
The capabilities of the Python language allow you to perform much more complex types of programming operations on the internal content of text files. For example, if you want to determine the number of lines in the file in Python, you can open the file and loop to count the number of lines it contains. A pre-defined variable, count, in which you write 0 before you use it and then add one for each new line, helps you do this.
count = 0 with open(r "D:test.txt", "r") as file: for line in file: count += 1 print(count)
The above example shows how the count counter works. To manipulate it, open the text file in read mode and then increment the previously declared numeric variable at each new step of the for loop, which is then printed. You can also do it another way. Read the file into a list using readlines. And after that use function len to determine the size of the list. This will be the number of lines.
with open(r "D:test.txt", "r") as file: print(len(file.readlines()))
Searching for a line
To use Python to find a line in a text file, you should resort to the built-in readlines method, which allows you to automatically read the inner contents of the file. As before, you must first open test.txt for reading and then place the data from it into a special array called lines. The built-in index method lets you find the number of an element in the sequence by simply passing it the right object, such as the string “second”.
with open(r "D:test.txt", "r") as file: lines = file.readlines() print(lines.index("secondn"))
Since all elements in test.txt are placed in separate lines, we must add the “n” clause to the line, which must be passed to the index method as an argument.
Removing a String
To delete a line from a file in Python, you must use two file handling modes at once: read and write. First, you need to open test.txt for reading to put the information from it into a separate array called lines. Next, you need to delete one of the elements in the sequence using the del operator and put the index of the necessary line in square brackets. The resulting array of objects should be placed in the source text file, but this time you need to open it in burn mode.
with open(r "D:test.txt", "r") as file: lines = file.readlines() del lines with open(r "D:test.txt", "w") as file: file.writelines(lines)
The above example of a small program demonstrates how to delete a line from a file. In this case, the readlines and writelines methods are used to read an array of lines from a document and write them there as well, separating the individual list elements.
Thus, it is quite easy to interact with the contents of text files using the Python 3 programming language. Its built-in functions allow you to write data into a document and read it out in a user-friendly way. With advanced file management tools, it is possible to manage files at a much more advanced level.