by Cristina | Aug 4, 2021 | Python
Random number file writer – In this lesson we will develop a simple algorithm for adding a random number to a file in Python.
Suppose we have a file that contains a number.
First we print the number contained in the file, then we generate a random number and add it to the number contained in the file.
Then we add the two numbers and add the resulting number to the file, starting with a new line.
Assuming the number_random.txt file contains the number 6, let’s try this example code:
import random
f = open('number_random.txt', 'r +')
number = f.readline()
print(number)
random_number = random.randint(1, 100)
print(random_number)
sum = random_number + int(number)
print(sum)
f.write('\ n' + str(sum))
f.close()
You must use the r + mode to be able to open a file for reading and writing at the same time.
Also remember that the write() method wants a string, so we need to convert the number obtained from reading the file into a string using casting with str().
Random number file writer – second example
In this second example we will try to guess the number that is contained in the number.txt text file.
Assuming the file contains only one number, we open the file in read-only mode and read the number. Then we ask what the number contained in the file is and give a victory or defeat message after comparing it.
Let’s develop a possible algorithm that solves our problem using also a simple function:
f = open('number.txt', 'r')
number = f.readline()
def guess(num):
if num == number:
return True
my_number = input('What number is contained in the file ?:')
result = guess(my_number)
if result:
print('You guessed it!')
else:
print('You didn't guess')
print('The number was:' + number)
f.close()
Random number file writer – third example
Now let’s modify the algorithm giving help to the user. Each time the user tries to guess, he will be told if the number thought is lower or higher than the one contained in the text file.
All for 5 times.
When we are faced with a complex problem we have to break it down into subproblems to make it easier.
So let’s first develop the simplest case, i.e. just one answer:
f = open('number.txt', 'r')
number = f.readline()
def guess(num):
if num == number:
return 0
elif num > number:
return 1
else:
return 2
my_number = input('What number is contained in the file ?:')
result = guess(my_number)
if result == 0:
print('You guessed it!')
elif result == 1:
print('The number to guess is lower')
else:
print('The number to guess is higher')
f.close()
Now we generate the 5 attempts, making sure to end the game when the attempts are finished or when you guess.
We generate a first solution in which we will exit the cycle through the use of break:
f = open('number.txt', 'r')
number = f.readline()
def guess(num):
if num == number:
return 0
elif num > number:
return 1
else:
return 2
attempts = 5
for i in range(attempts):
my_number = input('What number is contained in the file ?:')
result = guess(my_number)
if result == 0:
print('You guessed it!')
break
elif result == 1:
print('The number to guess is lower')
else:
print('The number to guess is higher')
f.close()
Now let’s create a new function thus avoiding the use of the break:
f = open('number.txt', 'r')
number = f.readline()
def guess(num):
if num == number:
return 0
elif num > number:
return 1
else:
return 2
attempts = 5
found = False
def game():
for i in range(attempts):
my_number = input('What number is contained in the file ?:')
result = guess(my_number)
if result == 0:
print('You guessed it!')
return
elif result == 1:
print('The number to guess is lower')
else:
print('The number to guess is higher')
game()
f.close()
In this lesson we have developed some algorithms such as adding a random number in a file in Python, or guessing the number contained in a text file. In the next few lessons we will practice the files again.
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
by Cristina | Aug 4, 2021 | Python
In this lesson we will study how to write to text file in Python, using the append mode and we will give some examples.
How to write to text file in Python – first example
In this first example we will use our address_book.txt file which already contains data and add new contacts.
For example, let’s assume that the file contains these contacts:
Name: cristina – Telephone: 3567
Name: luisa – Telephone: 34789
Let’s implement an algorithm that allows you to add new data using the write method:
f = open('address_book.txt', 'a')
name = input('Enter a new name:')
telephone = input('Enter telephone:')
f.write('Name:' + name + '- Telephone:' + telephone)
f.close()
We can also use the print function to write to the file, where we specify the file to write to which we previously opened with open:
f = open('address_book.txt', 'a')
name = input('Enter a new name:')
telephone = input('Enter telephone:')
print('Nome:' + name + ' - Telefono:' + telephone, file = f)
f.close()
How to write to text file in Python – second example
In this second example, manage multiple entries thanks to cyclic instructions.
For example, suppose you want to ask the user how many names you want to add to the file and consequently manage the inputs based on the answer given.
This is a possible implementation of the simple algorithm in which we use the for loop:
f = open('address_book.txt', 'a')
n_data = int(input('How much data do you want to insert ?:'))
for i in range(n_data):
name = input('Enter a new name:')
telephone = input('Enter telephone:')
f.write('\ nName:' + name + '- Telephone:' + telephone)
f.close()
How to write to text file in Python – third example
If we want to add more elements, we can also use an iterative instruction and terminate, for example, when clicking on a character of your choice.
Let’s say we want to enter some data and stop when we choose to type the character *.
Here is a possible implementation in which we use the while loop:
f = open('address_book.txt', 'a')
print('Insert new contacts in the address book, to finish insert * in the name')
name = input('Enter a new name:')
while name! = '*':
telephone = input('Enter telephone:')
f.write('\ nName:' + name + '- Telephone:' + telephone)
name = input('Enter a new name:')
f.close()
I take this opportunity to remember that the for loop is used when we know exactly how many times the loop will be executed, as in the second example where n_data will be executed. While the while loop is used when you want to stop the loop following a condition.
In this lesson we have seen some simple examples of how to add content to a file in Python.
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
by Cristina | Aug 4, 2021 | Python
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
by Cristina | Aug 4, 2021 | Python
In this lesson we will talk about Python readlines() method, which reads the entire text file and returns a list.
Python readlines() – first example
In this first example we will read our rubric.txt file using this readlines, let’s see what happens. So here’s a possible example:
f = open('address_book.txt', 'r')
contact = f.readlines()
print(contact)
f.close()
Using print on the list will print all the data it contains. In our case it will print: [‘Name: cristina – Telephone: 3567 \ n’, ‘Name: luisa – Telephone: 34789’].
We can see that each element also contains end-of-line characters, that is ‘\ n’.
In order to then print each row individually we can use an iterative instruction. But since each element contains the newline character we can use end in the print function.
Here is a possible solution:
f = open('address_book.txt', 'r')
contact = f.readlines()
for row in contact:
print(row, end=' ')
f.close()
By running the code we will now see the data printed like this:
Name: cristina – Telephone: 3567
Name: luisa – Telephone: 34789
Python readlines() – second example
We can also specify the number of lines to be read. To do this, just specify a number within the readlines() method.
So let’s take a simple example:
f = open('address_book.txt', 'r')
contact = f.readlines(1)
for row in contact:
print(row, end=' ')
f.close()
By entering readlines(1), only the first contact will be printed: Name: cristina – Telephone: 3567
Obviously, in this case, the cycle would not be needed.
Attention, if the number of bytes returned is greater than the number then it will not print any more lines.
In fact, let’s try to replace the value 1 with 2: f.readlines (2), in this case the second line will not be returned.
Let’s try another file, for example number_random.txt which contains this data:
6
25
100
f = open('address_book.txt', 'r')
contact = f.readlines(2)
for row in contact:
print(row, end=' ')
f.close()
In this case we will print the first and second lines:
6
25
This is because the number of bytes returned does not exceed the value indicated in brackets.
In this lesson we have studied Python readlines() method and developed examples in order to better understand how it works.
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
by Cristina | Aug 4, 2021 | Python
In this lesson we will study Python readline() method required for reading a text file.
This method returns a line of characters, including the newline character, which is the \ n character.
Python readline() – first example
Let’s take a first example on an address book file that contains the following example contacts:
Name: cristina – Telephone: 3567
Name: coding – Telephone: 34789
We open the file using the open function, specifying the reading mode (r). Then we apply Python readline() method and try to print the read text.
f = open ('address_book.txt', 'r')
contact = f.readline()
print(contact)
f.close()
The following code will print the first line only: Name: cristina – Telephone: 3567.
As we can see, the execution of readline() produces the reading up to the newline character, that is \ n.
Ultimately this method uses a cursor that represents a numeric index starting from 0 and increasing by 1 for each character read.
If we try to run readline() again we will read the second line, as the index has been increased.
f = open ('address_book.txt', 'r')
contact = f.readline()
print(contact)
contact = f.readline()
print(contact)
f.close()
But clearly this code for reading a text file is not ideal. Let’s try using a loop.
Python readline() – second example
We reason that we will stop reading when we encounter the null string, as it represents the end of the file.
So let’s implement a possible solution:
f = open ('address_book.txt', 'r')
contact = f.readline()
while contact != "":
print(contact)
contact = f.readline()
f.close()
We note that each contact in the address book will occupy two lines as the print function adds an additional newline character.
To avoid this problem we could use the print function with the end parameter, like so:
print (contact, end = “”), alternatively you can use the rstrip() method.
For in loop
An alternative to using readline in Python to be able to read a file is the for in loop.
Let’s see a simple example:
f = open ('address_book.txt', 'r')
for contact in f:
print(contact.rstrip())
f.close()
Ultimately we are treating the file as if it were simply a list of strings.
Conclusions
In this lesson we studied Python readline() method for reading data from a text file. We have also seen that it is not the only way to be able to read a text file.
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