In this post, you will learn file handing (create, read, append, write, delete files in python) in python.
In Python, there is a means of file handling. You can do some operations with a file such as opening a file, reading from it, writing into it, closing it and delete it etc.
Python File Handling
What is file handling in Python and how to create, write, append, read, delete files? Before knowing this, we know what the file is.
What is the file?
A file is one in which some data/information store is kept. And these files reside in the local computer system.
Whenever we want to do some operation with a file. Like read the file, write etc. So before that we have to open the file. And after our work is done, we also have to close the file.
Hence, in Python, a file operation takes place in the following order.
- Open a file
- Read or write (perform operation)
- Close the file
Open a file in python?
Now we will know how to open a file in Python.
Python has an in-built function. Whose name is open (). Basically Python file open () is used to open a file.
Let’s take an example, in this we will open a file:
>>> f = open("myfile.txt") # open file in current directory >>> f = open("C:/Python33/README.txt") # specifying full path
You know how to open files in python by using open (). But you know one more thing which is very important in the open() function.
When you open a file in Python. So the file you open can open that file in many modes.
In which mode we can open the file. Surrey Modes is described below:
Mode | Description |
---|---|
‘r’ | Open a file for reading. (default) |
‘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) |
‘b’ | Open in binary mode. |
‘+’ | Open a file for updating (reading and writing) |
You have seen that in which mode you can open the file in Python.
Now we take an example and understand how to use these modes when we open the file:
f = open("myfile.txt") # equivalent to 'r' or 'rt' f = open("myfile.txt",'w') # write in text mode
Close a file in Python?
You learned how to open a file in Python in various ways. Now you will learn how to close the file after operating with the file.
Because when opening a file, it is also necessary to close it.
Python also has a function called close (). You can use the close () function of Python to close the file.
Below we will do a file and after that we will also close it using Python close () function:
f = open("myfile.txt",encoding = 'utf-8') # perform file operations f.close()
Read files in Python?
You have learned to open and close the file open in Python. Now you will learn how to read the file.
Note: – Before reading the file in Python, the file has to be opened.
To read a file in Python, you can use the in-built function read () of Python.
How to read a file in Python. Let’s take an example to understand it better. In this example we will first open a file and then use Python’s in-built function read () to read the file. You can see the example below:
>>> f = open("myfile.txt",'r',encoding = 'utf-8') >>> f.read(4) # read the first 4 data 'This' >>> f.read(4) # read the next 4 data ' is ' >>> f.read() # read in the rest till end of file 'my first file\nThis file\ncontains three lines\n'
Now we will talk about another way by which you can read the file. You can also read files in Python with the help of for loop.
Let’s take an example of how to read files with the help of for loop:
f = open("myfile.txt", "r") for x in f: print(x) #output """This is my first file This file contains three lines"""
Python has another method. Whose name is readline () method. You can also read the file using this method.
Python Readline () method is used and read the file. The example is given below:
f = open("myfile.txt", "r") print(f.readline())
Write to File Using Python?
So far learned to open, close and read the file in python. Now we will learn how to write in a file and if the file is not exhausted then how to create it in python.
When you use the write method with a file in Python. Then you keep some things in mind and use this write () method. If you did not pass the correct mode, then the content in the file can be destroyed.
"a"
– Append – will append to the end of the file
"w"
– Write – will overwrite any existing content
f = open("myfile.txt", "a") f.write("Now the file has more content!") f.close()
Delete File in Python
This is the last topic of this post. Now we will learn how to delete files.
To tell you one thing, to delete a file, the dew module has to be imported into Python. You cannot delete files in Python without importing the dew module.
Let’s take an example of how to delete a file in Python with the help of dew module. From this you will understand very well how to do the file with the help of dew module:
import os os.remove("myfile.txt")
Python You can also delete a folder with a file using the dew module.
Below you can see an example of how we deleted the folder in Python using the dew module:
import os os.rmdir("myfolder")
File Methods in Python
We have also provided a list below. In which a method to work with a Python file is given. And we have taken the example of most of the methods. Which you must have seen.
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. |