如何在列中搜索变量,然后使用Python 3打印出包含csv文件中数字的所有行

时间:2018-10-05 21:38:37

标签: python python-3.x csv

我正在编写一个程序,该程序检查CSV中的数字,然后打印出整行。第四个是数字。这是我尝试过的:

 with open('Info.csv', 'r') as csv_file
 if 'View C' in choice:
        read = csv.reader(csv_file)
        view = str(input("Enter Number: "))
        for column in read:
            if view == column[3]:
                print(row)

csv文件的结构如下:

John,Smith,London,131390890
Bob,Builder,Moscow,123123132
Dab,God,LA,131390890

我希望程序像这样:

输入:

123123132

输出:

Bob,Builder,Moscow,123123132,

它还需要具备以下功能:

输入:

131390890

输出:

John,Smith,London,131390890,
Dab,God,LA,131390890,

谢谢!

顺便说一句,使用Python 3 ...

2 个答案:

答案 0 :(得分:1)

您可以使用列表理解。要查找具有您要查找的编号的行,请阅读整个文件,并将每行追加到名为content的列表中。然后:

result = [i for i in content if i[-1] == 'your_number']

这样,变量result将包含N行,每行的最后一列与您的电话号码相符

答案 1 :(得分:0)

使用loc根据列中的值对DataFrame进行子集化。假设列的名称为whichever_column_your_number_exists,而您要查找的值为view。另外,请确保该列的数据类型与您要搜索的值view相同。

df = pd.read_csv('Info.csv') #Read your CSV file
your_df = df.loc[df['whichever_column_your_number_exists'] == view] #Assuming view is str type

然后遍历新DataFrame yourdf的每一行,并在每一列中打印值。

for row in your_df.index:
    print(df.at[row, column1_name], df.at[row, column2_name], df.at[row, column3_name], df.at[row, column4_name]