有一个包含大约 2000 条记录的 CSV 文件。
每条记录都有一个字符串和一个类别:
This is the first line,Line1 This is the second line,Line2 This is the third line,Line3
我需要将此文件读入如下列表:
data = [('This is the first line', 'Line1'), ('This is the second line', 'Line2'), ('This is the third line', 'Line3')]
如何使用 Python 将此 CSV 导入到我需要的列表中?
您可以使用 Python 的内置csv模块读取 CSV 文件并将其转换为所需的元组列表。操作方法如下:
csv
import csv # Path to your CSV file csv_file_path = 'your_file.csv' # Initialize an empty list to store the data data = [] # Open the CSV file and read its content with open(csv_file_path, mode='r', newline='', encoding='utf-8') as file: reader = csv.reader(file) for row in reader: data.append((row[0], row[1])) # Print the result to verify print(data)
在此代码中:
csv_file_path
with open(csv_file_path, mode='r', newline='', encoding='utf-8') as file:
csv.reader(file)
for row in reader:
data.append((row[0], row[1]))
data
确保将其替换'your_file.csv'为 CSV 文件的实际路径。运行此代码后,data将包含所需的元组列表。
'your_file.csv'