Python File Handling
In this tutorial, you will learn about python File Handling.
What is File?
File is a named location on disk to store related information. It is used to store data permanently in a non-volatile memory(hard disk).
While performing operation on file, first we need to open it. And after performing the operation it needs to be closed. So that resources that are tied with the file are freed.
So here Python File handling takes in following order:
- Opening a file.
- Performing operations(read, write etc.).
- Closing the file.
Opening a File
Before performing the read/write operation, you first need to open the file.
Syntax of opening a file is:
f = open(filename, mode)
open()
function accepts two arguments filename
and mode
. filename
is a string argument which specify filename along with it’s path and mode
is also a string argument which is used to specify how file will be used i.e for reading or writing. And f
is a file handler object also known as file pointer.
Eg: f = open('MyTextFile.txt', 'w')
Closing a File
After finishing the file operation, you need to close the file so the resources allocated to file will be freed.
You can perform this using close()
method. Below is the syntax:
f.close() # where f is the pointer to the file
Different Modes of Opening a File
MODES | DESCRIPTION |
---|---|
“r” | Open a file in read mode |
“w” | Open a file in write mode. If file already exists its data will be cleared before opening. Otherwise new file will be created. |
“a” | Opens a file in append mode i.e to write at the data to the end of the file. |
“wb” | Open a file to write in binary mode. |
“rb” | Open a file to read in binary mode. |
Reading Keyboard Input
Python provides two built-in functions to read a line of text from standard input, which by default comes from the keyboard.
These functions are :
- raw_input
- input
The raw_input Function
The raw_input([prompt]) function reads one line from standard input and returns it as a string (removing the trailing newline).
eg:
[pastacode lang=”python” manual=”str%20%3D%20raw_input(%22Enter%20your%20input%3A%20%22)%3B%0Aprint%20%22Input%20is%20%3A%20%22%2C%20str%0A%0A%23%20Output%3A%0A%23%20Enter%20your%20input%3A%20Hello%20there%0A%23%20Input%20is%20%3A%20%20Hello%20there” message=”The raw_input() function in Python” highlight=”” provider=”manual”/]
The input Function
It is similar to raw_input function, except that it assumes the input is a valid Python expression and returns the evaluated result to you.
eg:
[pastacode lang=”python” manual=”str%20%3D%20input(%22Enter%20your%20input%3A%20%22)%0Aprint%20%22Input%20is%20%3A%20%22%2C%20str%0A%0A%23%20Output%3A%0A%23%20Enter%20your%20input%3A%20%5Bx*5%20for%20x%20in%20range(2%2C10%2C2)%5D%0A%23%20Input%20is%20%3A%20%20%5B10%2C%2020%2C%2030%2C%2040%5D%0A” message=”input function in python” highlight=”” provider=”manual”/]
Reading data from the file
Python provides three methods to read data from the file :
METHODS | DESCRIPTION |
---|---|
read([number]) | Return specified number of characters from the file. if omitted it will read the entire contents of the file. |
readline() | Return the next line of the file. |
readlines() | Read all the lines as a list of strings in the file |
Reading whole data from the file at once
[pastacode lang=”python” manual=”f%20%3D%20open(‘myfirstfile.txt’%2C%20’r’)%0Af.read()%20%23%20read%20entire%20content%20of%20file%20at%20once%0A%22this%20first%20line%5Cnthis%20second%20line%5Cn%22%0Af.close()” message=”Reading whole data from a file” highlight=”” provider=”manual”/]
Reading all lines as an array
[pastacode lang=”java” manual=”f%20%3D%20open(‘mytextfile.txt’%2C%20’r’)%0Af.readlines()%20%23%20read%20entire%20content%20of%20file%20at%20once%0Af.close()%0A%09%0A%23Out%20will%20be%20like%20%3E%5B%22this%20first%20line%5Cn%22%2C%20%22this%20second%20line%5Cn%22%5D” message=”Reading lines from file as an array” highlight=”” provider=”manual”/]
Reading only one line from file
[pastacode lang=”python” manual=”f%20%3D%20open(‘myfile.txt’%2C%20’r’)%0Af.readline()%20%23%20read%20one%20of%20file%20%0Af.close()%0A%0A%23Output%20will%20like%20%3E%20%22this%20first%20line%5Cn%22″ message=”Reading only one line from file” highlight=”” provider=”manual”/]
Writing data into the file
You will use write()
function to write data into the file.
Note: write()
method will not insert new line (‘\n’) automatically like print function, you need to explicitly add '\n'
while writing to file from write()
method.
[pastacode lang=”python” manual=”f%20%3D%20open(‘myfile.txt’%2C%20’w’)%20%20%20%20%20%20%20%23%20open%20file%20for%20writing%0Af.write(‘this%20is%20the%20first%20line%5Cn’)%20%20%20%20%20%20%20%23%20write%20a%20line%20to%20the%20file%0Af.write(‘this%20is%20the%20second%20line%5Cn’)%20%20%23%20write%20second%20line%20into%20the%20file%0Af.write(‘this%20is%20the%20third%20line%5Cn’)%20%20%20%20%23%20write%20third%20%20line%20into%20the%20file%0Af.close()%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20close%20the%20file%0A%0A%23%20Output%20will%20be%20something%20like%3A%0A%23%20this%20is%20the%20first%20line%0A%23%20this%20is%20the%20second%20line%0A%23%20this%20is%20the%20third%20line” message=”Writing data into the file using write() method” highlight=”” provider=”manual”/]
Appending data into the file in python
While appending the data into the file, you must use the append mode “a”.
[pastacode lang=”python” manual=”with%20open(%22test.txt%22%2C%20%22a%22)%20as%20myfile%3A%0A%20%20%20%20myfile.write(%22appended%20text%22)%0Amyfile.close()” message=”Appending data into file using with” highlight=”” provider=”manual”/]
Binary reading and writing of File in Python
To perform binary read/write, you need to use a module called pickle. Pickle module allows you to read and write data using load and dump method respectively.
Writing Binary Data
You will use dump()
method of pickle
module to write binary data and mode will be "wb"
.
[pastacode lang=”python” manual=”%3E%3E%20import%20pickle%0A%3E%3E%3E%20f%20%3D%20open(‘binaryfile.dat’%2C%20’wb’)%0A%3E%3E%3E%20pickle.dump(11%2C%20f)%0A%3E%3E%3E%20pickle.dump(%22this%20is%20a%20line%22%2C%20f)%0A%3E%3E%3E%20pickle.dump(%5B2%2C%204%2C%206%2C%208%5D%2C%20f)%0A%3E%3E%3E%20f.close()” message=”Writing into binary file using dump() method” highlight=”” provider=”manual”/]
Reading Binary Data
You will use load()
method of pickle
module to read binary data and mode will be "rb"
.
[pastacode lang=”python” manual=”%3E%3E%20import%20pickle%0A%3E%3E%3E%20f%20%3D%20open(‘binaryfile.dat’%2C%20’rb’)%0A%3E%3E%3E%20pickle.load(f)%0A11%0A%3E%3E%3E%20pickle.load(f)%0A%22this%20is%20a%20line%22%0A%3E%3E%3E%20pickle.load(f)%0A%5B2%2C4%2C6%2C8%5D%0A%3E%3E%3E%20f.close()” message=”Reading data from file using load() method” highlight=”” provider=”manual”/]
Note: If there is no more data to read from file, pickle.load(f)
will throw EOFError
or end of file error.
File handling methods of Python OS module
The "os"
module of Python provides various functions which are used to perform various operations on Files. To use these functions module "os"
needs to be imported.
Method | Description |
---|---|
rename() | It is used to rename a file. It takes two arguments, existing_file_name and new_file_name. |
remove() | It is used to delete a file. It takes one argument. Pass the name of the file which is to be deleted as the argument of method. |
mkdir() | It is used to create a directory. A directory contains the files. It takes one argument which is the name of the directory. |
chdir() | It is used to change the current working directory. It takes one argument which is the name of the directory. |
getcwd() | It gives the current working directory. |
rmdir() | It is used to delete a directory. It takes one argument which is the name of the directory. |
tell() | It is used to get the exact position in the file. |
-
rename():
import os os.rename('oldfile.txt','newfile.txt')
- remove():
import os os.remove('file.txt')
- mkdir():
import os os.mkdir("new directory")
- chdir():
import os os.chdir("changed directory")
- getcwd():
import os print os.getcwd()
- rmdir():
import os os.rmdir("dir_name")
Note: In order remove directory, it should be empty. If it is not then first delete the files in the directory.
Nice tutorial..Very informative…