[英]Reading comma separated values from text file in python
I have a text file consisting of 100 records like我有一个包含 100 条记录的文本文件,例如
fname,lname,subj1,marks1,subj2,marks2,subj3,marks3.
I need to extract and print lname and marks1+marks2+marks3 in python.我需要在python中提取和打印lname和marks1+marks2+marks3。 How do I do that?
我该怎么做?
I am a beginner in python.我是python的初学者。
Please help请帮忙
When I used split, i got an error saying当我使用 split 时,我收到一条错误消息
TypeError: Can't convert 'type' object to str implicitly.
类型错误:无法将“类型”对象隐式转换为 str。
The code was代码是
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
If you want to do it that way, you were close.如果你想这样做,你就很接近了。 Is this what you were trying?
这是你尝试的吗?
file = open(file_name, 'r')
for line in file.readlines():
fname = line.rstrip().split(',') #using rstrip to remove the \n
print fname
Note: its not a tested code.注意:它不是经过测试的代码。 but it tries to solve your problem.
但它试图解决您的问题。 Please give it a try
请试一试
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.'
"""
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.