如何在python中使用fileinput.input获取每行的值

时间:2019-03-27 13:20:11

标签: python

我有这个csv:

mycsv.csv

name,last name  
yeison, smith
lola, boa
elmo, spitia
anderson, exneider
juan, ortega

我想显示每列的值。像这样:

print (line["word"])
print (line[0])


import fileinput

with fileinput.input('mycsv.csv', inplace=True) as f:
 for line in f:
    #if f.lineno() == 2:
    if line["name"] == "yeison":
        print('german, ezequiel')
    else:
        print(line, end='')

2 个答案:

答案 0 :(得分:4)

您可以使用此简单的代码来读取cvs文件(熊猫)

# Load the Pandas libraries with alias 'pd' 
import pandas as pd 
# Read data from file 'filename.csv' 
# (in the same directory that your python process is based)
# Control delimiters, rows, column names with read_csv (see later) 
data = pd.read_csv("filename.csv") 
# Preview the first 5 lines of the loaded data 
data.head()

答案 1 :(得分:0)

如果数据不大,您可以打开并逐行解析文件,如下所示:

with open("mycsv.csv") as f:
    lines = [line.strip('\n') for line in f]

for ln in lines:
    abc = ln.split(',')
    if(len(abc) > 1):
        print(abc[0],abc[1])

否则,您可以使用csv模块有效地做到这一点