Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python implementing a class supporting text file read and write

Python implementing a class supporting text file read and write

Document Object Reference Manual Python3 Examples

We will create a class named TextFileHandler class, which will support reading and writing text files. This class will contain two main methods:read_file for reading file content,write_file for writing content to a file.

Example

class

TextFileHandler:

   

def

init

(

self

,

filename

)

:

       

self

.

filename

=

filename

   

def

read_file

(

self

)

:

       

try

:

           

with

open

(

self

.

filename

,

'r'

)

as

file

:

                content

=

file

.

read

(

)

           

return

content

       

except

FileNotFoundError:

           

return

"File not found."

   

def

write_file

(

self

,

content

)

:

       

with

open

(

self

.

filename

,

'w'

)

as

file

:

           

file

.

write

(

content

)

       

return

"File written successfully."

Example usage

handler

=

TextFileHandler

(

'example.txt'

)

handler.

write_file

(

"Hello, World!"

)

print

(

handler.

read_file

(

)

)

Code analysis:

  1. __init__ Method: this is the class constructor, used to initialize an instance of the class. It accepts a file name as a parameter and stores it in the instance variable self.filename it.
  2. read_file Method: this method is used to read file content. It uses with open statement to open the file in read mode and read its content. If the file does not exist, it catches FileNotFoundError exception and returns "File not found.".
  3. write_file Method: this method is used to write content to a file. It uses with open statement to open the file in write mode and write the passed content to the file. After successful writing, it returns "File written successfully.".

Output result:

Hello, World!

Document Object Reference Manual Python3 Examples