orest
0
Q:

for line in text file python

with open("file.txt") as file_in:
    lines = []
    for line in file_in:
        lines.append(line)
21
with open(filename) as f:
    content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content] 
5
# Python code to 
# demonstrate readlines() 
  
L = ["Geeks\n", "for\n", "Geeks\n"] 
  
# writing to file 
file1 = open('myfile.txt', 'w') 
file1.writelines(L) 
file1.close() 
  
# Using readlines() 
file1 = open('myfile.txt', 'r') 
Lines = file1.readlines() 
  
count = 0
# Strips the newline character 
for line in Lines: 
    print("Line{}: {}".format(count, line.strip())) 
5
# Python program to 
# demonstrate reading files 
# using for loop 
  
L = ["Geeks\n", "for\n", "Geeks\n"] 
  
# Writing to file 
file1 = open('myfile.txt', 'w') 
file1.writelines(L) 
file1.close() 
  
# Opening file 
file1 = open('myfile.txt', 'r') 
count = 0
  
# Using for loop 
print("Using for loop") 
for line in file1: 
    count += 1
    print("Line{}: {}".format(count, line.strip())) 
  
# Closing files 
file1.close() 
1

New to Communities?

Join the community