Python - File Text File

Introduction

To scan a text file line by line, file iterators are often your best option:

Demo

myfile = open('myfile.txt', 'w')        # Open for text output: create/empty 
myfile.write('hello text file\n')       # Write a line of text: string 
myfile.write('goodbye text file\n') 
myfile.close()                          # Flush output buffers to disk 
#  www  . j a v  a  2 s .c o m
for line in open('myfile.txt'):        # Use file iterators, not reads 
     print(line, end='')

Result

Related Topics