Home >Backend Development >Python Tutorial >How to read txt data in python
Methods to read TXT data in Python: Direct reading: Use the open() function to open the file and read the content. Read line by line: Use the readlines() function to read each line in the file. Use third-party libraries: csv library: Use a CSV reader to read content line by line. pandas library: Use the read_csv() function to read the entire file.
How to use Python to read TXT data
Read directly
The easiest way is to use Python's open()
function to read the TXT file directly.
<code class="python"># 打开文件并读取内容 with open("my_file.txt", "r") as f: data = f.read()</code>
Read line by line
To read a TXT file line by line, you can use the readlines()
function.
<code class="python"># 打开文件并逐行读取内容 with open("my_file.txt", "r") as f: lines = f.readlines()</code>
Use third-party libraries
There are also some third-party libraries that can help read TXT data, such as csv
or pandas
.
Usecsv
Library:
<code class="python">import csv # 打开文件并使用 CSV 读取器读取内容 with open("my_file.txt", "r") as f: reader = csv.reader(f) data = list(reader)</code>
Use pandas
Library:
<code class="python">import pandas as pd # 使用 Pandas 读取文件 data = pd.read_csv("my_file.txt")</code>
Notes
with
statement to properly close the file. The above is the detailed content of How to read txt data in python. For more information, please follow other related articles on the PHP Chinese website!