What is a text file 2

Read files and use content

Reading files with Python is not a big problem. We want to load data from a file and we can then process it further as we wish.

The file itself that we want to load with Python should be in the same directory. We create a text file with the content "Text that comes from file". The file name should meet the usual criteria. You don't even have to assign a file extension - I do this purely out of habit and call my text file “textfile.txt”.

Text coming from a file

To load this file now, we create a Python program in the same directory as our text file.

In the first step we have to open the file for reading.

So far nothing has happened, because we have to specify the type of use in in the MODE. There are different modes for reading a file, writing to a file or reading and writing at the same time.

The following abbreviations are available for the mode:

wfor "write" - write only (existing content will be overwritten)
afor "append" - is appended to existing content
rfor "read" - only for reading (see r +)
r +so reading and writing
bIn binary form for reading and writing (the other modes are supplemented by b)

We want to first read our content from the file, so we use the "read only" mode.

So far so good. What does the function actually deliver back to us? This provides us with a return value on which we can then use various methods.

The return value we get: "<_io.TextIOWrapper name = 'textfile.txt' mode = 'r' encoding = 'UTF-8'>"

Now we can apply the available methods to it such as.

We are now shown the content "Text coming from file".

Let us now expand the content of our file "textfile.txt" by 2 more lines:

Text coming from a file
I am the second line
and the third follows immediately

Don't forget to save. If we now apply our method to it again, we see the complete content as the result (no matter how many lines there are).

Always read out only 1 line via

However, if we only want to read out one line in order to process the content of the file line by line, the method helps. For example, we have saved a numerical value in each line and want to read them in and process them one by one:

If we now apply our existing program to it:

We only get the first line.

In order to read in line by line, we wrap the method in a loop:

Now it is run through line by line:

Set length of reading over

With the method, the length of the reading can be specified in the brackets. Thus, for example, the first 5 characters can be read out.

As a result, we now receive the first seven characters of our sample text as return:

If the seventh character were a line break, this would then be read and output as the last character. Just try it once :).

Good style - finish over

It is a matter of good style that we announce to the system that we have "finished using" the file. Therefore, the connection is closed again via the method after reading and writing processes

Recommend • Social Bookmarks • Thank you