Professional Documents
Culture Documents
Most importantly there are 4 types of operations that can be handled by Python on files:
Open
Read
Write
Close
Other operations include:
Rename
Delete
Opening Files
Python has an in-built function called open() to open a file. It takes two string arguments:
1. The file path including the file name and the extension we want to open, is to be passed as a string
2. The mode in which we want to open the file, to be passed as a string.
The syntax for opening a file:
Syntax:
file_object = open(file_name, mode)
# open a file
file1 = open("test.txt", "r")
# read the file
read_content = file1.read()
print(read_content)
Output
This is a test file.
Hello from the test file
Write to a File in Python
The write() method:
This function inserts the string into the text file on a single line.
If we want to add content to existing file, test.txt, first we need to open it in the ‘w’ write mode and
use the .write() method on file.
For example,
# open a file
file1 = open("test.txt", "r")