简体   繁体   中英

Reading comma separated values from text file in python

I have a text file consisting of 100 records like

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

I need to extract and print lname and marks1+marks2+marks3 in python. How do I do that?
I am a beginner in python.

Please help

When I used split, i got an error saying

TypeError: Can't convert 'type' object to str implicitly.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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