我有一个由100条记录组成的文本文件,例如
fname,lname,subj1,marks1,subj2,marks2,subj3,marks3.
我需要在python中提取并打印lname和marks1 + marks2 + marks3。我该怎么做?
我是python的初学者。
请帮忙
当我使用split时,我收到错误
TypeError:无法隐式地将'type'对象转换为str。
代码是
import sys
file_name = sys.argv[1]
file = open(file_name, 'r')
for line in file:
fname = str.split(str=",", num=line.count(str))
print fname
答案 0 :(得分:1)
注意:它不是经过测试的代码。但它试图解决你的问题。请试一试
import csv
with open(file_name, 'rb') as csvfile:
marksReader = csv.reader(csvfile)
for row in marksReader:
if len(row) < 8: # 8 is the number of columns in your file.
# row has some missing columns or empty
continue
# Unpack columns of row; you can also do like fname = row[0] and lname = row[1] and so on ...
(fname,lname,subj1,marks1,subj2,marks2,subj3,marks3) = *row
# you can use float in place of int if marks contains decimals
totalMarks = int(marks1) + int(marks2) + int(marks3)
print '%s %s scored: %s'%(fname, lname, totalMarks)
print 'End.'
答案 1 :(得分:1)
如果你想这样做,你就近了。这是你在尝试的吗?
file = open(file_name, 'r')
for line in file.readlines():
fname = line.rstrip().split(',') #using rstrip to remove the \n
print fname
答案 2 :(得分:0)
"""
sample file content
poohpool@signet.com; meixin_kok@hotmail.com; ngai_nicole@hotmail.com; isabelle_gal@hotmail.com; michelle-878@hotmail.com;
valerietan98@gmail.com; remuskan@hotmail.com; genevieve.goh@hotmail.com; poonzheng5798@yahoo.com; burgergirl96@hotmail.com;
insyirah_powergals@hotmail.com; little_princess-angel@hotmail.com; ifah_duff@hotmail.com; tweety_butt@hotmail.com;
choco_ela@hotmail.com; princessdyanah@hotmail.com;
"""
import pandas as pd
file = open('emaildump.txt', 'r')
for line in file.readlines():
fname = line.split(';') #using split to form a list
#print(fname)
df1 = pd.DataFrame(fname,columns=['Email'])
print(df1)