In Python, we can use built-in functions to read and write text files. Here are some basic operations:
read text file
We can use Python's built-in open()
function to open a text file. open()
The function needs to pass two parameters. The first parameter is the file path and file name, and the second parameter is the mode of opening the file. Common modes include r
read-only mode and w
Indicates write mode. Here is a sample code for reading a text file:
with open('example.txt', 'r') as file:
content = file.read()
print(content)
write to text file
We can use Python's built-in open()
function to open a text file. open()
The function needs to pass two parameters. The first parameter is the file path and file name, and the second parameter is the mode of opening the file. Common modes include r
read-only mode and w
Indicates write mode. Here is a sample code that writes to a text file:
with open('example.txt', 'w') as file:
file.write('Hello, world!')
In the above code, we with
have opened a example.txt
file named using the statement and written w
a string Hello, world!
to the file using the pattern.
append text file
If we need to append new content to a text file, we can a
open the file using a mode, as follows:
with open('example.txt', 'a') as file:
file.write('\\nThis is a new line.')
In the above code, we with
have opened a example.txt
file called using the statement and using a
the pattern to This is a new line.
write the string to a new line in the file.