DEV Community

Cover image for Python File Basics
Abdessamad Bensaad
Abdessamad Bensaad

Posted on

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")
Enter fullscreen mode Exit fullscreen mode

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:

mode what allows you to do?
r: Opens the file in read-only mode. Starts reading from the beginning of the file and is the default mode for the open() function.
rb: Opens the file as read-only in binary format and starts reading from the beginning of the file. While binary format can be used for different purposes, it is usually used when dealing with things like images, videos, etc.
r+: Opens a file for reading and writing, placing the pointer at the beginning of the file.
w: Opens in write-only mode. The pointer is placed at the beginning of the file and this will overwrite any existing file with the same name. It will create a new file if one with the same name doesn't exist.
wb: Opens a write-only file in binary mode.
w+: Opens a file for writing and reading.
wb+: Opens a file for writing and reading in binary mode.
a: Opens a file for appending new information to it. The pointer is placed at the end of the file. A new file is created if one with the same name doesn't exist.
ab: Opens a file for appending in binary mode.
a+: Opens a file for both appending and reading.
ab+: Opens a file for both appending and reading in binary mode.

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.

  • name - file name;
  • mode - the mode in which this file is open;
  • closed- returns Trueif the file has been closed.

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()

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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'

Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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")

Enter fullscreen mode Exit fullscreen mode

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")

Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)