You are on page 1of 1

Please follow this example as it is for you to answer exercise 5

Example.txt

Hi.
This is a text file.
Let us Start!

There are several ways on how to read the content of the text file

To load the content of text file line by line, use this code
( 1)

lines = [line.strip() for line in open('example.txt')]

The string method strip removes any whitespace characters from the beginning and end of a string.
Use rstrip if you need to preserve whitespace at the beginning of the line.

(2)

s = open('example.txt').read()

There are also several ways to write to files. We will look at one way here. We will be writing to a file
called writefile.txt.

f = open('writefile.txt', 'w')
print('This is line 1.', file=f)
print('This is line 2.', file=f)
f.close()

A program the reads the content of temps.txt, Add 5 to the values, and save/write to another textfile
named ftemps.txt

file1 = open('ftemps.txt', 'w') //textfile to write the final value


temperatures = [line.strip() for line in open('temps.txt')] //reading the content of textfile
for t in temperatures: //accessing the individual values
x = int(t) + 5 //operation performed on the values
print(x) //test to show the output
print(x, file=file1) //sending the final value to the specified textfile
file1.close()

Sana magawa nyo na!!!

You might also like