Nearby lessons
77 of 108Python - Read Files
Detailed Tutorial Notes
6) Output
7) sunny
8) bunnEg 3: To read data line by line:
🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
sunny bunny chinny
Eg 4: To read all lines into list:
🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
sunny bunny chinny vinny
Eg 5:
🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
sun ny
11)
12) bunn
13) Remaining data
14) y
15) chinny
16) vinnyThe with statement:
The with statement can be used while opening a file.We can use this to group file
operation statements within a block.
The advantage of with statement is it will take care closing of file,after completing all
operations automatically even in the case of exceptions also, and we are not required to
close explicitly.
Eg:
🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
Is File Closed: False Is File Closed: True
The seek() and tell() methods:
tell():
==>We can use tell() method to return current position of the cursor(file pointer) frombeginning of the file. [ can you plese telll current cursor position]
The position(index) of first character in files is zero just like string index.
Eg:
1) f=open("abc.txt","r")
2) print(f.tell())
3) print(f.read(2))
4) print(f.tell())
5) print(f.read(3))
6) print(f.tell())abc.txt:
sunny
bunny
chinny
vinny
🧠 Test Your Knowledge
5 QuestionsProgress: 0 / 5
Keep Going!Python - Write Files