Python provides support for working with files. Using python’s in-built functions, you can create new files and write content to them, read existing files, appending content to files and deleting files.
Opening a file
For performing any operation on a file, it needs to be opened. This is done by using python’s built-in open function. This function returns a stream pointing to the file. It takes following arguments:

filePath of the file to be opened. This argument is mandatory.
modeA string which specifies the operation that could be performed once file is opened. It can be any of the following
‘r’    : File is opened in read mode(default). Throws error if file does not exist.
‘w’   : File opened for writing. Creates file if it does not exist.
‘x’    : Create new file and open it for reading. Creates file if it does not exist.
‘a’    : Appends text to the end of file, creates the file if it does not exist.
‘b’    : For opening binary files.
‘t’     : For opening text files(default).
‘r+’  : For opening files in read and write mode.
‘w+’ : For opening files in read and write mode.
This argument is optional.
bufferingIndicates whether the file contents should be buffered. Default is -1. Negative buffering means system settings will be used. 0 means no buffering, 1 means only a single line of file will be buffered at once. Any other positive value indicates the size of buffer. This argument is optional.

File will be created if it does not exist only when it is opened in ‘w’, ‘a’, ‘w+’ or ‘a+’ modes else you will get an error.

When trying to open a file which does not exist, “FileNotFoundError: [Errno 2] No such file or directory” error is raised.

Reading a File
Once a file is opened and its stream is assigned to a variable, the file can be read. Python provides two methods to read a file.

  1. read() : This method can be used to read a file in chunks or whole file at once. It takes an integer as argument which represents the number of characters that will be read from the file when this method is invoked. If the argument is -1 or omitted, complete file is read at once.
  2. readline() : This method is used to read a file line by line. A single invocation of this method returns one line of the file.

Note that both these methods return a string and when any of the above methods is invoked, the cursor moves ahead and subsequent calls to these methods will return the content ahead of that cursor position. Example, suppose we have a file named demo.txt with below contents

Python is a versatile language. It is easy to learn and has several features.

Now go through the below program very carefully to understand the usage of above methods.

file_object = open("f:/demo.txt")  # open file in read mode
content = file_object(10)          # reads 10 characters and stores them in variable
print(content)                     # prints "Python is"
content = file_object.readline()   # reads a line from the current cursor position 
print(content)                     # prints "a versatile language." 
content = file_object.readline()   # reads next line from the current cursor position  
print(content)                     # prints "It is easy to learn and has several features."
content = file_object.readline()   # reads next line from the current cursor position
print(content)                     # prints nothing
file_object.close()                # close the file

When read method is called with 10, it reads 10 characters from the start of file. Next when readline is called, it reads the current line and the cursor reaches the end of first line. Again when readline is called, it reads the next line of file and the cursor reaches the end of second line. Finally, when readline is again called, it returns an empty string since there is nothing to read after the cursor position.

It is a good practice to close the file after reading is complete.

Repositioning the cursor
Once the file is read completely, you cannot read it again from the start simply by calling read or readline methods since python’s file reading mechanism works on a cursor which moves forward when any of these methods is called and reaches the end of file when the file is read completely. In order to read the file again, you can close the file and open it again. This will place the cursor at the beginning of the file.

There is another way also which is seek method. This method takes an integer as argument which represents the current character position at which you want the cursor to move. A value of 0 to this method will place the cursor at the beginning of file. For the same file as above, refer the examples to understand this method. Remember that the first character of file is at position 0, second at position 1 and so on.

file_object = open("f:/demo.txt")  # open file in read mode
content = file_object.readline()   # reads first line
print(content)                     # prints "Python is a versatile language." 
content = file_object.readline()   # reads next line from the current cursor position  
print(content)                     # prints "It is easy to learn and has several features."
file_object.seek(0)                # position cursor at the start of file
content = file_object.readline()   # reads next line from the current cursor position
print(content)                     # prints "Python is a versatile language."
file_object.seek(7)                # position cursor at 7th position
content = file_object.readline()   # reads next line from the current cursor position
print(content)                     # prints "is a versatile language."
file_object.close()                # close the file

Writing Files
Python’s file handling library provides a method write to add text to a file. This method takes a string argument which is the content that needs to be written to the file. write method takes a string as a parameter which is the content that is written to the file. This means that the content written to a file is always a string. For writing to a file, the file needs to be opened in any of ‘w’, ‘a’, ‘r+’, ‘w+’ or ‘a+’ modes. Example,

file_object = open('f:/demo.txt', 'w')   # open a file for writing
file_object.write('Writing to file')     # write content to file
file_object.close()                      # close the file
file_object = open('f:/demo.txt', 'r')   # open file again for reading
content = file_object.readline()         # read current line
print(content)                           # prints "Writing to file"
file_object.close()                      # close the file

Remember that you will not see any contents written on the file unless you close the file using close method or call flush method after calling write method.  Content written by write method is not directly written to the file, it is first written to in-memory buffers. Content from these buffers is written when the file is closed or these buffers are forced to pop it out. flush method flushes out the content of these buffers to the file.
Also note that if an already existing file is opened in ‘w’, ‘w+’ or ‘r+’ modes, its previous contents will be overwritten. If some new content is to be written and previous contents also needs to be preserved then open the file in ‘a’ or ‘a+’ modes.

If you open a file in ‘r'(read) mode and you invoke write method on the file object, then you get an UnsupportedOperation error as io.UnsupportedOperation: not writable If you open a file in ‘w'(write) mode and you invoke read method on the file object, then also you get as UnsupportedOperation error. 
0

Share your thoughts !!

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.