Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python Programming Working Using a for Loop to Read Text Files

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Programming Working Using a for Loop to Read Text Files

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Python

programming
Using a For Loop to Read Text Files
In addition to using the readline() method above to
read a text file, we
can also use a for loop. In fact, the for loop is a more
elegant and
efficient way to read text files. The following
program shows how this is
done.
f = open (‘myfile.txt’
,
'r')
for line in f:
print (line, end = ‘’)
f.close()
The for loop loops through the text file line by line.
When you run it,
you’ll get
Learn Python in One Day and Learn It Well Python
for
Beginners with Hands-on Project The only book you
need
to start coding in Python immediately
Writing to a Text File
Now that we’ve learned how to open and read a file,
let’s try writing to it.
To do that, we’ll use the ‘a’ (append) mode. You can
also use the ‘w’
mode, but you’ll erase all previous content in the file
if the file already
exists. Try running the following program.
f = open (‘myfile.txt’
,
'a')
f.write(‘\nThis sentence will be appended.’)
f.write(‘\nPython is Fun!’)
f.close()
Here we use the write() function to append the two
sentences ‘This
sentence will be appended.’ and ‘Python is Fun!’ to
the
file, each starting on a new line since we used the
escape characters
‘\n’. You’ll get
Learn Python in One Day and Learn It Well Python
for
Beginners with Hands-on Project The only book you
need
to start coding in Python immediately
http://www.learncodingfast.com/python This
sentence
will be appended.
Python is Fun!

You might also like