繁体   English   中英

从python中的文本文件中读取逗号分隔值

[英]Reading comma separated values from text file in python

我有一个包含 100 条记录的文本文件,例如

fname,lname,subj1,marks1,subj2,marks2,subj3,marks3.

我需要在python中提取和打印lname和marks1+marks2+marks3。 我该怎么做?
我是python的初学者。

请帮忙

当我使用 split 时,我收到一条错误消息

类型错误:无法将“类型”对象隐式转换为 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

如果你想这样做,你就很接近了。 这是你尝试的吗?

file = open(file_name, 'r')

for line in file.readlines():
    fname = line.rstrip().split(',') #using rstrip to remove the \n
    print fname

注意:它不是经过测试的代码。 但它试图解决您的问题。 请试一试

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM