Python read txt file
Reading TXT Files with Python
In Python, there are many ways to read and process text files. This article will introduce several methods for reading TXT files, including both regular text files and CSV format files.
Opening Files
In Python, you can open a text file using the open()
function. The open()
function requires two parameters: a file name and an open mode. The file name can be an absolute or relative file path. There are several different open mode options, the most commonly used of which are:
r
: Read-only mode. The text file must exist; otherwise, an error will be reported.w
: Write mode. If the text file already exists, the existing contents will be overwritten; if not, a new file will be created.a
: Append mode. If the text file exists, the new content is appended to the end of the file. If the text file does not exist, a new file is created.
After opening a file, you can use the readline()
method to read the text file line by line.
The following is an example of reading a file:
with open('example.txt', 'r') as f:
for line in f:
print(line.strip())
This code opens the text file named example.txt
in read-only mode. The with
statement ensures that the file is properly closed after reading. The for
loop reads the text file line by line and uses the strip()
method to remove spaces and newlines from the end of each line.
Reading an Entire File
If you need to read an entire text file at once, you can use the read()
method. The read()
method reads the entire file into a string.
The following is an example of reading an entire file:
with open('example.txt', 'r') as f:
content = f.read()
print(content)
Reading CSV Files
In addition to ordinary text files, Python can also read and process CSV format files. CSV files are files that separate values using commas and are commonly used to store tabular data.
In Python, you can use the csv
module to read CSV files. The csv
module provides the reader()
and writer()
methods for reading and writing CSV files.
The following is an example of reading a CSV file:
import csv
with open('example.csv') as f:
reader = csv.reader(f)
for row in reader:
print(row)
This code reads a file named example.csv
using the csv.reader()
method to read the file contents. The for
loop iterates through each line and prints the output.
Conclusion
In Python, you can use the open()
function to read text files. You can use the readline()
method to read a file line by line, or you can use the read()
method to read the entire file at once. For CSV files, you can use the csv
module to read and process the file contents.