Home > OS >  .read() method and looping through the io.TextIOWrapper object
.read() method and looping through the io.TextIOWrapper object

Time:12-25

When line 2 is executed, the code does not run the for loop. if i removed line 2 it will run the for loop

fhand=open("file.txt")
print(fhand.read()) #line 2
lineCount=1
print("="*20)
for line in fhand:
    print("Line ",lineCount,": ",line.rstrip())
    lineCount =1

I want to run .read() method to show the file content and aslo loop through file content line by line to add certain text

CodePudding user response:

change it from fhand.read() to fhand.readlines() then you will get list of lines

fhand=open("file.txt")
print(fhand.readlines()) #change it to readlines()
lineCount=1
print("="*20)
for line in fhand:
    print("Line ",lineCount,": ",line.rstrip())
    lineCount =1

CodePudding user response:

And I think you need to put in a variable:

fhand = open("file.txt")
read_fhand = fhand.readlines()
print(read_fhand)
line_count = 1
print("=" * 20)
for line in read_fhand:
    print("Line ", line_count, ": ", line.rstrip())
    line_count  = 1
  • Related