Python too supports file handling and allows users to handle files i.e., to read, write, create, delete and move files, along with many other file handling options, to operate on files. The concept of file handling has stretched over various other languages, but the implementation is either complicated or lengthy, but alike other concepts of Python, this concept here is also easy and short.
The main focus of this article will be on the following topics.
Creating a File
The first step in using a file instance is to open a disk file. In any computer language this means establishing a communication link between your code and the external file. To create a new file I/O classes provides the member function
Here the mode refers to the Access Mode. Access modes govern the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. These modes also define the location of the File Handle in the file. File handle is like a cursor, which defines from where the data has to be read or written in the file. There are 6 access modes in python.
- Read Only (‘r’): Open text file for reading. The handle is positioned at the beginning of the file. If the file does not exists, raises I/O error. This is also the default mode in which file is opened.
- Read and Write (‘r+’): Open the file for reading and writing. The handle is positioned at the beginning of the file. Raises I/O error if the file does not exists.
- Write Only (‘w’): Open the file for writing. For existing file, the data is truncated and over-written. The handle is positioned at the beginning of the file. Creates the file if the file does not exists.
- Write and Read (‘w+’): Open the file for reading and writing. For existing file, data is truncated and over-written. The handle is positioned at the beginning of the file.
- Append Only (‘a’): Open the file for writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
- Append and Read (‘a+’): Open the file for reading and writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
Example: Suppose the folder looks like this –
In the above example,
open() function along with the access mode ‘w+’ is used to open a file in writing and reading mode but if the file doesn’t exist in the computer system then it creates the new file.
Note: To know more about creating a file click here.
Reading from File
There are three ways to read data from a text file.
- read(): Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire file.
- readline(): Reads a line of the file and returns in form of a string.For specified n, reads at most n bytes. However, does not reads more than one line, even if n exceeds the length of the line.
- readlines(): Reads all the lines and return them as each line a string element in a list.
‘\n’ is treated as a special character of two bytes.
Output of Read function is Hello This is Delhi This is Paris This is London Output of Readline function is Hello Output of Read(9) function is Hello Th Output of Readline(9) function is Hello Output of Readlines function is ['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']
Note: To know more about reading from file click here.
Writing to File
There are two ways to write in a file.
- write(): Inserts the string str1 in a single line in the text file.
- writelines(): For a list of string elements, each string is inserted in the text file. Used to insert multiple strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]
‘\n’ is treated as a special character of two bytes.
Hello This is Delhi This is Paris This is London
Note: To know more about writing to file click here.
This can be achieved using
shutil.move() function from shutil module.
shutil.move() method Recursively moves a file or directory (source) to another location (destination) and returns the destination. If the destination directory already exists then src is moved inside that directory. If the destination already exists but is not a directory then it may be overwritten depending on
Example: Suppose the directory looks like this –
Note: To know more about moving files click here.
Deleting a File
os.remove() method in Python is used to remove or delete a file path. This method can not remove or delete a directory. If the specified path is a directory then OSError will be raised by the method.
Example: Suppose the file contained in the folder are:
We want to delete the file1 from the above folder. Below is the implementation.
Note: To know more about deleting files click here.
- HDF5 files in Python
- Working with PDF files in Python
- Writing CSV files in Python
- Reading CSV files in Python
- Downloading files from web using Python
- Working with csv files in Python
- Working with zip files in Python
- How to move Files and Directories in Python
- Writing files in background in Python
- Python | Reading .ini Configuration Files
- Python | How to use Multiple kv files in kivy
- Listing out directories and files in Python
- Rename multiple files using Python
- Python | Merge two text files
- Python | Arrange the files in directories according to extensions
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.