[英]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.