Handling files in python

by Alex
Handling files in python

File interactions in the Python programming language provide the user with the ability to store information that has been processed by the application so that it can be accessed later at any convenient time. The basic functions of this language make it fairly easy to create, write, and read data from files.

Creating and opening

To be able to work with a file in Python 3, you must first create it. This can be done with the standard means of the operating system by going to the desired directory and creating a new document with txt format. However, the same action is performed by using the open method of the Python programming language, to which you need to pass the file name and its processing mode as parameters. The following code shows how to get a variable file reference to a new document. If you run this program, it will create a text file test.txt in the folder where the source code is stored.

file = open("test.txt", "w")
file.close()

If, however, a file named test.txt already exists in the code directory, the program will simply continue working with it without creating a new document. As you can see, the file name is the first parameter of the open method. It is immediately followed by a special letter that denotes the data processing method. In this case, “w” stands for write. For now, it is important to remember that after all manipulations on the file, it is imperative to close it using the close function in order to guarantee that no information is lost. In the previous example, to access the file we used a relative path, which does not contain exhaustive information about the location of the object on your hard drive. In order to set them, you should write an absolute path as the first argument of the open function. In this case the test.txt document will be located at the root directory of the D drive and not in the program folder.

file = open(r "D:test.txt", "w")
file.close()
We used r before the string literal to disable the escape character. Otherwise, the compiler will consider the sequence “t” as a tab character and throw an exception.

Opening mode

The special characters that are used in Python when opening a file were mentioned earlier. They set the opening mode of the file. They tell the program exactly how to open it. They are all presented in the following table, which contains their signature and a short description of their purpose.

Symbol Value
“r” read opening (default)
“w” opening for writing, and if it does not exist on the specified path, a new one is created
“x” opening for writing, but only if it does not already exist, otherwise an exception will be thrown
“a” opening for an additional record, so that the information is added to the end of the document
“b” opening in binary mode
“t” opening in text mode (default)
“+” opening for reading and writing simultaneously

Using the second argument of the open method, you can combine different file modes by specifying, for example, “rb” to read written data in binary mode. Another example: The difference between “r+” and “w+” is that in the second case a new file will be created, if there is no such file. In the first case, however, an exception occurs. When using “r+” and “w+” the file will be opened for both reading and writing. Let’s see an example of exception handling when we are going to examine file reading.

Methods

The object returned by the open function contains a reference to an existing file. It also contains information about the created document represented in the form of four main fields. They are all described in the following table, which contains their names and values.

Property Value
name returns the file name
mode returns the mode in which the file was opened
closed true if the file is closed and true if it is opened
softspace returns true if no space character should be added separately when outputting data from the file

To display the properties of a file, just use the access operator, i.e. a dot, and then pass this as a parameter to the already familiar print function. For example:

f = open(r "D:test.txt", "w")
print(f.name)
f.close()

D:test.txt

Write

In Python 3, writing to a file is done using the write method. This method is called from an object that refers to an existing file. It is important to remember that to do this, you must first open the document using the open function and specify the write mode with the “w” character. The write method takes as its argument the data you want to put into a text file. The following code example shows the writing of the string “hello”.

file = open("test.txt", "w")
file.write("hello")
file.close()

If you want to add new information to the previously written data, call the open function again, giving it the “a” operating mode. Otherwise, all information from the test.txt file will be completely deleted. In the code example below, the text document is opened for additional writing and then the string literal ” world” is placed in it with a space at the beginning. Thus “hello world” will be placed in test.txt. After all of this, you should not forget about the mandatory closing of the file.

file = open("test.txt", "a")
file.write(" world")
file.close()

This is the easiest way to write data into a text file. Note that the Python programming language contains a lot of additional features for more advanced manipulation of documents that also include advanced writing.

Writing Binary Data

When writing binary data, you should use “wb” mode. Here is an example of writing a utf8-encoded string:

f = open('test.dat', 'wb')
f.write(bytes('string', 'utf8'))
f.close()

Reading

To read information from a file in Python 3, you should call the read method through an object that references an existing document. You should also remember to specify “r” as the second parameter of the open function when opening a text file. In the following example, read returns the information from test.txt to the print method, which then displays the information on the screen. As before, the program ends by closing the document using the close method. The read method can also accept an integer parameter that is used to pass the number of characters to be read. For example, by entering 5, the program will only read hello.

try:
    file = open("test.txt", "r")
    print(file.read())
    file.close()
except FileNotFoundError:
    print('Not found')
except IOError:
    print('Something else')
Note that an error may occur when opening. For example, if the specified file is not found. So we had to handle an exception. In Python you can use a with statement and in that case you will not have to handle exceptions or even close the file. We will discuss it below.

There is one more thing: you cannot do a closure in the finally section of the try block. If an exception occurs when the file is opened, there will be an error in the finally section.

Reading Binary Data

If the data is binary, you should use “rb” in the open function. Let’s look at an example:

try:
    f = open("test.dat", "rb")
    b = f.read(1)
    str = ""
    while True:
        b = f.read(1)
        if b == b':
            break
        str += b.hex()
    print(str)
    f.close()
except IOError:
    print('error')

81d182d180d0bed0bad0b0

This reads the file byte for byte. Each byte is converted to string form in hexadecimal representation. The resultant string is printed with the print function.

with as

To automate the processing of text files a bit, it is recommended to use a bunch of operators with as. They eliminate the need to call the close method for a document that you want to close, because it is done automatically. This is shown in the next code snippet, which reads data from test.txt. As usual, the print method is used to print the string information to the screen.

with open('test.txt', 'r') as file:
    print(file.read())

Moreover, in this case there is no need to handle an exception. If there is no file with the specified name, the lines with embedded code in the with statement will not be executed. With the above features of the Python programming language, the user is able to perform basic operations on reading and writing information to files quite easily.

Related Posts

LEAVE A COMMENT