How to read or write files in Python?

Before any files to read we have to know how to Open & Close the files.

# Open Function:

we can open a file using python build in function open()

file_object = open(file_name, file_access_mode )
  • file_name = It is the file name or the full file path.
  • file_access_mode = File access mode is to determine, open file for read, write , append etc.
ModesDescription
rOpens a file for read only purpose.
rbOpen a file for reading only in binary format.
r+Open a file for both operation reading & writing.
rb+Open a file for both reading & writing in binary format.
wOpen a file for writing purpose only.
It overwrites the existing file or otherwise create a new file.
wbOpens a file for writing only in binary format.
It overwrites the existing file or otherwise create a new file.
aOpens a file for appending.
abOpens a file for appending in binary format.
ab+Opens a file for both appending & reading in binary format.
w+Opens a file for both reading & writing format.
wb+Opens a file for both reading & writing in binary format.

# Write Function:


file_content = "This is my First Text."
file_object.write( file_content ) 

# Read Function:

file_object.read()

# Rename Files:

os.rename( old_file_name, new_file_name )

# Delete File:

os.remove( file_name )

# Close File:


file_object.close()

# File Object Attributes:

  • file_object.closed
  • file_object.mode
  • file_object.softspace [ It is no longer supported in python 3.x ]
  • file_object.name

Leave a Comment