.read() method and looping through the io.TextIOWrapper object
Question:
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
Answers:
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
In python when you want to read a file you must use the code bellow:
f = open("file.txt", "r")
file = f.read()
Now the file
will contain all the text file information.
To write thing into a file you must:
file = open("file.txt", "w")
file.write('text')
file.close()
you could also change the w
inside the open function to an a
to add text
to the original text file.
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
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
In python when you want to read a file you must use the code bellow:
f = open("file.txt", "r")
file = f.read()
Now the file
will contain all the text file information.
To write thing into a file you must:
file = open("file.txt", "w")
file.write('text')
file.close()
you could also change the w
inside the open function to an a
to add text
to the original text file.