Python: 如何从特定的 lines/columns/rows 中读取数据

Python: How to read data from specific lines/columns/rows

在我的 CSV 文件中有 10 行数据,每行包含 1 个人的帐户详细信息。

这里是我的文件的 2 行,例如:

姓名:电子邮箱:密码

Matt,Matt@gmail.com,123456
John,John@gmail.com,123456

所以现在在我的 python 脚本中假设我想获取第 2 行的电子邮件 (John@gmail.com),该怎么做?

这应该可以,当然你需要安装 pandas。

import pandas as pd
df = pd.read_csv('your.csv',header=False)
print(df[1][1])

您可以使用 pandas 从 CSV 中仅加载某些行。

代码:

import pandas as pd

# Select second row
row_to_select = 2
input_file = '/content/sample_2.csv'

# You can use skiprows to skip unwanted rows
data = pd.read_csv(infile, skiprows=lambda x: x not in range(row_to_select, row_to_select+1))

# Convert the column dataframe to list if necessary
print(list(data))

输出:

['John', 'John@gmail.com', '123456']