Interact with files in Python
Last Updated :
04 Jan, 2023
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 open(). Syntax:
open(filename, mode)
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 –
Python3
file1 = open ("MyFile.txt","w + ")
|
Output:
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.
File_object.read([n])
- 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.
File_object.readline([n])
- readlines(): Reads all the lines and return them as each line a string element in a list.
File_object.readlines()
Note: ‘\n’ is treated as a special character of two bytes.
Python3
file1 = open ("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
file1.write("Hello \n")
file1.writelines(L)
file1.close()
file1 = open ("myfile.txt", "r + ")
print ("Output of Read function is ")
print (file1.read())
print ()
file1.seek( 0 )
print ("Output of Readline function is ")
print (file1.readline())
print ()
file1.seek( 0 )
print ("Output of Read( 9 ) function is ")
print (file1.read( 9 ))
print ()
file1.seek( 0 )
print ("Output of Readline( 9 ) function is ")
print (file1.readline( 9 ))
print ()
file1.seek( 0 )
print ("Output of Readlines function is ")
print (file1.readlines())
print ()
file1.close()
|
Output:
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. File_object.write(str1)
- 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]
Note: ‘\n’ is treated as a special character of two bytes.
Python3
file1 = open ( 'myfile.txt' , 'w' )
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
s = "Hello\n"
file1.write(s)
file1.writelines(L)
file1.close()
file1 = open ( 'myfile.txt' , 'r' )
print (file1.read())
file1.close()
|
Output:
Hello
This is Delhi
This is Paris
This is London
Note: To know more about writing to file click here.
Moving File
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 os.rename() semantics. Example: Suppose the directory looks like this –
Inside G:
Python3
import shutil
source = "D:\Pycharm projects\gfg\Test\Test4.txt"
destination = "D:\Pycharm projects\gfg\Test\G"
dest = shutil.move(source, destination)
|
Output:
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.
Python3
import os
file = 'file1.txt'
location = "D: / Pycharm projects / GeeksforGeeks / Authors / Nikhil / "
path = os.path.join(location, file )
os.remove(path)
|
Output:
Note: To know more about deleting files click here.
Similar Reads
File Objects in Python
A file object allows us to use, access and manipulate all the user accessible files. One can read and write any such files. When a file operation fails for an I/O-related reason, the exception IOError is raised. This includes situations where the operation is not defined for some reason, like seek()
6 min read
Read a file without newlines in Python
When working with files in Python, it's common to encounter scenarios where you need to read the file content without including newline characters. Newlines can sometimes interfere with the processing or formatting of the data. In this article, we'll explore different approaches to reading a file wi
2 min read
Open Python Files in IDLE in Windows
IDLE works well for inexperienced and seasoned Python programmers alike as it integrates into the Python interpreter, interactive shell, and debugging tools for learning Python, testing code, and building Python applications. Although some developers may opt for more feature-rich IDEs in their compl
2 min read
fileinput.input() in Python
With the help of fileinput.input() method, we can get the file as input and can be used to update and append the data in the file by using fileinput.input() method. Python fileinput.input() Syntax Syntax : fileinput.input(files) Parameter : fileinput module in Python has input() for reading from mul
2 min read
Writing to file in Python
Writing to a file in Python means saving data generated by your program into a file on your system. This article will cover the how to write to files in Python in detail. Creating a FileCreating a file is the first step before writing data to it. In Python, we can create a file using the following t
4 min read
Inventory Management with File handling in Python
Inventory management is a crucial aspect of any business that deals with physical goods. Python provides various libraries to read and write files, making it an excellent choice for managing inventory. File handling is a powerful tool that allows us to manipulate files on a computer's file system us
5 min read
File Mode in Python
In Python, the file mode specifies the purpose and the operations that can be performed on a file when it is opened. When you open a file using the open() function, you can specify the file mode as the second argument. Different File Mode in PythonBelow are the different types of file modes in Pytho
5 min read
Writing files in background in Python
How to write files in the background in Python? The idea is to use multi-threading in Python. It allows us to write files in the background while working on another operation. In this article, we will make a 'Asyncwrite.py' named file to demonstrate it. This program adds two numbers while it will al
2 min read
File Handling in Python
File handling refers to the process of performing operations on a file such as creating, opening, reading, writing and closing it, through a programming interface. It involves managing the data flow between the program and the file system on the storage device, ensuring that data is handled safely a
7 min read
Open a File in Python
Python provides built-in functions for creating, writing, and reading files. Two types of files can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). Text files: In this type of file, each line of text is terminated with a special character called EOL
6 min read