Python File Object - codebugfree

 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")

There are mainly three types of file objects they are:
1) Binary files
2) Text files
4) Raw files
my_file = open("file_name.txt","w")


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.

Method                      Description
read()                         Read the given file.
readline()                   Read the given file but only one line read.
readlines()                 Read files to a list.
readable()                  Return files stream read or not read.
truncate()                   Compress or resize the files.
write()                       Write any things to given file.
writeline()                 Write any things for only one line given file.
close()                       Close the open file.
writeable()                Return the files stream written or not written.
tell()                          Return the current files position.
flush()                       flush if internal buffer their.

Program of python file object

1) read()

with open("file-objects.txt","r")as f:
    read_file =


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()


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()


['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")


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.

Post a Comment