Press ESC to close

Python read()

0 177

In this lesson we will study the Python read() method.

Let’s start with a simple example that uses the address_book.txt file, the quake contains two simple example contacts.

We open this file in read mode and then apply the Python read() method.


f = open('address_book.txt', 'r')

contact = f.read()
print(contact)

f.close()

The output will be:

Name: cristina – Telephone: 3567
Name: luisa – Telephone: 34789

If we indicate a number between the brackets we specify the number of characters to read.

f.read(14)

In this case, the output will be: Name: cristina

Python read() – second example

In this example we read all the data from a file, then create a list using the splitlines() method.

This is a simple example of using the following method:


f = open('address_book.txt', 'r')

contact = f.read()
print(contact)

array = contact.splitlines()
print(array)

f.close()

In this example we have read the contents of the address book file with the read method and then apply the splitlines() method to the string obtained in order to obtain a list.

The readlines() method we studied in the previous lesson also allows you to create a list. We have therefore developed another possible solution to creating a list starting from the content of a text file.

Python read() – third example

In this third example, after creating the list, we add new items to the created list and then copy them to the file.

To add items to the list we use the methods we have studied for lists.

Here is a possible implementation:


f = open('address_book.txt', 'r')

contact = f.read()
print('elements present \ n' + contact)

array = contact.splitlines()
print('transform into array')
print(array)

array.append('Name: Paolo - Phone: 2314')
print('The new array with the inserted data:')
print(array)

f = open('address_book.txt', 'w')

for i in array:
    f.write(i + '\ n')

f.read()
f.close()

These are just some simple examples of applying the Python read() method, in the next lesson we will develop some applications with this method.

Some useful links

Python tutorial

Python Compiler

Introduction to dictionaries in Python
Use Python dictionaries
Create dictionaries in Python
Python get() method
keys() method
items() method
pop() method
popitem() method
Sort dictionary in Python

Other stories

How to write to text file

Next Story

Python readlines()

Previous Story