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 
# from  w w w . j av  a2 s. co m
for line in open('myfile.txt'):        # Use file iterators, not reads 
     print(line, end='')

Result

Related Topics