In this section we learn about the python file object. Then practice how to python file objects method or attributes to perform a different task in different situation.
file objects in python |
file object is use in different python project. In beginner if we make the number guessing game high score is save in score.txt file than use to read and write than score.txt file.
What is file objects and types of file object
Python file object is gives programmer to access the file. Programmer do any things to file. such as read and write the file.Â
Python file objects use built in function open with(). Using it open the file and perform any task to the file. Syntax of file object.
my_file = open("file_objects.txt")
my_file = open("file_name.txt","w")
print(type(my_file))
INOUTPUT
class '_io.TextIOWrapper'
It is the example of file object. It is also a write mode file object example. Open file name is file_name.txt and mode is w. Means w for writeÂ
Python File Object Method
python has many files object method but her describe all file object method with example.
Program of python file object
1) read()
with open("file-objects.txt","r")as f:
read_file = f.read()
print(read_file)
INOUTPUT
this is a python file objects
section hope
you enjoy
Read method always read the file. If given file is not found or given file name spelling is mistake than face error FileNotFoundError.
2) readline()
with open("file-objects.txt","r")as f:
read_file = f.readline()
print(read_file)
INOUTPUT
this is a python file objects
Read line method always print the one line. Other line ignore.
3) readlines()
with open("file-objects.txt","r")as f:
read_file = f.readlines()
print(read_file)
INOUTPUT
['this is a python file objects\n', 'section hope \n', 'you enjoy']
Read lines always print string to list and also print where is line like \n.Â
4) write
with open("file-object.txt","w")as f:
f.write("this is a object method chapter")
INOUTPUT
this is a object method chapter
All text is over right. means old text we use to see the example of read text all automatic delete and write this new text.
0 Comments
Don't comment a spam message