Code Pumpkin

File I/O | Python

November 4, 2018
Posted by Dipen Adroja

In this article, we will learn how we can do File I/O operation in python. We briefly go through how to open a file, reading from it, writing into it, closing it and along with that various methods are available for file operations. File is a physical location on disk to store related information.

If we want to read from or write to a file first we need to open it and once done with our task we have to close it. So the operations can be as followed:

  • Open a file
  • Read/Write operation for file
  • Close the file

How to Open A file in Python?

Python has a built-in read() function to open a file. This function returns the object of the file, it also called handle as it provides control for reading/modifying the file.

We can also specify mode in which we want to open a file. We can open a file in text mode('t') or binary mode('b'). We can also specify whether we want to read 'r', write 'w' or append 'a' to the file. The default is reading in text mode, we get strings when reading from the file. In python, unlike other languages character 'a' doesn't imply the ascii number 97 until it is encoded in ASCII. It is highly recommended to specify the encoding type while working with text files.

Example:


my_file = open("myfile.txt")      # equivalent to 'r' or 'rt'
my_file = open("myfile.txt",'w')  # write in text mode
my_file = open("temp_img.bmp",'r+b') # read and write in binary mode
my_file = open("myfile.txt",mode = 'r',encoding = 'utf-8') # opening a file in read mode for utf-8 encoded file

Below table lists all the possible modes and its description.

   Mode    Description
'r' Open a file for reading. (default mode)
'w' Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
'x' Open a file for exclusive creation. If the file already exists, the operation fails.
'a' Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.
't' Open in text mode. (default mode)
'b' Open in binary mode.
'+' Open a file for updating (reading and writing)

How to read files in Python?

Once the file is opened, there are various methods available for reading the file. read(size) method is used for reading size data, if not specified it will return the complete file.


my_file = open("test.txt",mode = 'r',encoding = 'utf-8')
print(myfile.read(10)) # reads only 10 characters
print(myfile.read()) # read complete file

We can read a file line by line using for loop and is also an efficient and fast way.


for line in myfile:
    print(line, end = '')

Now if we want to read file line by line, we can use readline() method. This method reads a file till the newline, including the newline character.

We can also change the current file cursor using the seek() method. The same way tell() method returns our current position as shown below:


myfile.tell() # This will return the cursor position
myfile.seek() # This will bring file cursor to its initial position

How to Write files in Python?

In order to write into a file in Python, we need to open it in write 'w', append 'a' or exclusive creation 'x' mode. The 'w' mode will overwrite into the file if it already exists so, we should take care when using it. Writing a stream to file is done using write() method.


with open("test.txt",'w',encoding = 'utf-8') as myfile:
   myfile.write("my first file\n")
   myfile.write("This file\n\n")
   myfile.write("contains three lines\n")

Python File Methods

There are various methods available with the file object. Some of them have been used in the above examples.

Here is the complete list of methods in text mode with a brief description.

Method

Description

close()

Close an open file. It has no effect if the file is already closed.

detach()

Separate the underlying binary buffer from the TextIOBase and return it.

fileno()

Return an integer number (file descriptor) of the file.

flush()

Flush the write buffer of the file stream.

isatty()

Return True if the file stream is interactive.

read(n)

Read atmost n characters form the file. Reads till end of file if it is negative or None.

readable()

Returns True if the file stream can be read from.

readline(n=-1)

Read and return one line from the file. Reads in at most n bytes if specified.

readlines(n=-1)

Read and return a list of lines from the file. Reads in at most n bytes/characters if specified.

seek(offset,from=SEEK_SET)

Change the file position to offset bytes, in reference to from (start, current, end).

seekable()

Returns True if the file stream supports random access.

tell()

Returns the current file location.

truncate(size=None)

Resize the file stream to size bytes. If size is not specified, resize to current location.

writable()

Returns True if the file stream can be written to.

write(s)

Write string s to the file and return the number of characters written.

writelines(lines)

Write a list of lines to the file.

That's it for file I/O operations.

That's all for this topic. If you guys have any suggestions or queries, feel free to drop a comment. We would be happy to add that in our post. You can also contribute your articles by creating contributor account here.

Happy Learning 🙂



About the Author


Dipen Adroja
Coder, Blogger, Wanderer, Philosopher, Curious pumpkin



Tags: ,


Comments and Queries

If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code class="java"> 
String foo = "bar";
</code></pre>
For more information on supported HTML tags in disqus comment, click here.
Total Posts : 122
follow us in feedly
Contribute Your Articles

Subscribe Us

Like Us On Facebook