File I/O | Python
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
- 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
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 modemy_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
We can also change the current file cursor using the seek() method. The same way
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 |
|
---|---|
| 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. |
| Return an integer number (file descriptor) of the file. |
flush() | Flush the write buffer of the file stream. |
| Return True if the file stream is interactive. |
read(n) |
Read |
readable() | Returns True if the file stream can be read from. |
| Read and return one line from the file. Reads in at most n bytes if specified. |
| 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 |
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 |
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. |
| 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 🙂
If you like the content on CodePumpkin and if you wish to do something for the community and the planet Earth, you can donate to our campaign for planting more trees at CodePumpkin Cauvery Calling Campaign.
We may not get time to plant a tree, but we can definitely donate ₹42 per Tree.
About the Author
Tags: python, Python Tutorials
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.