January 27, 2023

Python File Basics

Interaction with the file system allows you to store information obtained as a result of the program. in this article, I will talk about the basic functionality of the Python programming language for working with files.

Built-in Python tools:

The basis for working with files - built-in function open()



open(file, mode="rt")


This function has two arguments. The argument file takes a string containing the path to the file. The second argument,, mode allows you to specify the mode in which you want to work with the file. By default, this argument takes the value " rt", which, and some others, can be found in the table below:

These modes can be combined. For example, "rb" opens a binary file for reading. By combining "r +" or "w +", you can achieve opening a file in the mode and reading and writing at the same time with one difference - the first mode will throw an exception if the file does not exist, and working in the second mode will create it in this case.

You can start working with the file using the class object io.TextIOWrapper returned by the function open(). This object has several attributes through which information can be obtained.

Upon completion of work with the file, it must be closed using the method close()



f = open("hello.md", "w")

# deal with this file

f.close()


However, the more pythonic way of working with a file inline is to use a construct with .. as .. that acts as a context creation manager. The example written above can be rewritten with its help



with open("hello.md", "w") as f:

# deal with this file


The main difference is that python closes the file on its own, and the developer does not need to remember this. And as a bonus, no exceptions will be thrown when the file is opened (for example, if the file does not exist).

Reading from a file:

There are several approaches you can take when opening a file in readable modes.

To begin with, you can read the entire file and write all the data in it on one line.



with open("hello.md", "r") as f:

    part = f.read(16)
    

By using this function with an integer argument, a certain number of characters can be read.



with open("hello.md", "r") as f:

    part = f.read(16)
    

Only the first 16 characters of the text will be received. It is important to understand that when using this function several times in a row, part by part of this text will be read - the virtual cursor will move by the reading part of the text. It can be moved to a specific position using the method if necessary seek().



with open("hello.md", "r") as f: # 'Hello, world!'

    first_part = f.read(8)       # 'Hello, w'
    
    f.seek(4)
    
    second_part = f.read(8)      # 'o, world'
    

Another way is to read the file line by line. The method readline() reads a line and, just like with the method read(), moves the cursor - only now by a whole line. Applying this method multiple times will result in multiple lines being read. Similar to this method, another method allows you to read the entire file, but line by line, by writing them to a list. This list can be used, for example, as an iterable in a loop.



with open("hello.md", "r") as f:

    for line in f.readlines():
    
        print(line)



However, there is a more pythonic way here too. It consists in the fact that the object itself io.TextIOWrapperhas an iterator that returns line by line. Thanks to this, there is no need to read the entire file, saving it to a list, but you can dynamically read the file line by line. And do it succinctly.



with open("hello.md", "r") as f:

    for line in f:
    
        print(line)
        

Write to file:

The functionality of entering data into a file does not depend on the mode - adding data or overwriting a file. There are also several approaches to performing this operation.

The simplest and most logical is to use a function write()



with open("hello.md", "w") as f:

    f.write("Hello from write function")


It is important that only strings can be passed as an argument to a function. If it is necessary to write another kind of information, then it must be explicitly cast to the string type using methods __str__(self) for objects or formatted strings.

It is possible to write a large amount of data to a file if it can be represented as a list of strings.



with open("hello.md", "w") as f:

    f.writelines("you can put some large data here")


There is one more thing that is associated with the fact that the functions write() and writelines() does not automatically put the symbol of a line break, and this developer need to control yourself.

There is another, less well-known, method, but perhaps the most convenient of the presented ones. And as strange as it may seem, it consists in using a function print(). At first, this statement may seem strange, because it is common knowledge that it is used to output to the console. And it is true. But if you pass an fileobject of type as an optional argument io.TextIOWrapper, which is the file object we are working with, then the output stream of the function is print() redirected from the console to the file.



with open("hello.md", "w") as f:

    print("put some data here", file=f)


The strength of this approach lies in the fact that print() you can pass not necessarily string arguments - if necessary, the function itself converts them to a string type.

This completes the acquaintance with the basic functionality of working with files. At the same time, it should be said that the capabilities of the Python language are not limited to them. There are a large number of libraries that allow you to work with certain types of files, and also allow for closer interaction with the file system. Together, they provide developers with an easy and comfortable way to work with files.

Keep reading😊

Text Link
Web development
Mobile development
coding tips
front-end
January 30, 2023

5 ways to align HTML element horizontally and vertically

Read more
marketing
SEO
February 7, 2023

7 Proven Strategies for Finding Clients for Your Business

Read more