我有一个CSV文件,下面是一个示例:
Year: Dec: Jan:
1 50 60
2 25 50
3 30 30
4 40 20
5 10 10
Run Code Online (Sandbox Code Playgroud)
我知道如何读取文件并打印每一列(例如 - ['Year', '1', '2', '3', etc]).但我真正想做的是读取行,这将是这样的['Year', 'Dec', 'Jan'],然后['1', '50', '60']依此类推.
然后我想将这些数字存储['1', '50', '60']到变量中,以便我可以在以后将它们合计为:
Year_1 = ['50', '60'].然后我就能做到sum(Year_1) = 110.
我将如何在Python 3中执行此操作?
Joe*_*ett 66
使用csv模块:
import csv
with open("test.csv", "r") as f:
reader = csv.reader(f, delimiter="\t")
for i, line in enumerate(reader):
print 'line[{}] = {}'.format(i, line)
Run Code Online (Sandbox Code Playgroud)
输出:
line[0] = ['Year:', 'Dec:', 'Jan:']
line[1] = ['1', '50', '60']
line[2] = ['2', '25', '50']
line[3] = ['3', '30', '30']
line[4] = ['4', '40', '20']
line[5] = ['5', '10', '10']
Run Code Online (Sandbox Code Playgroud)
Ash*_*ary 20
这样的事情:
with open("data1.txt") as f:
lis = [line.split() for line in f] # create a list of lists
for i, x in enumerate(lis): #print the list items
print "line{0} = {1}".format(i, x)
# output
line0 = ['Year:', 'Dec:', 'Jan:']
line1 = ['1', '50', '60']
line2 = ['2', '25', '50']
line3 = ['3', '30', '30']
line4 = ['4', '40', '20']
line5 = ['5', '10', '10']
Run Code Online (Sandbox Code Playgroud)
要么 :
with open("data1.txt") as f:
for i, line in enumerate(f):
print "line {0} = {1}".format(i, line.split())
# output
line 0 = ['Year:', 'Dec:', 'Jan:']
line 1 = ['1', '50', '60']
line 2 = ['2', '25', '50']
line 3 = ['3', '30', '30']
line 4 = ['4', '40', '20']
line 5 = ['5', '10', '10']
Run Code Online (Sandbox Code Playgroud)
编辑:
with open('data1.txt') as f:
print "{0}".format(f.readline().split())
for x in f:
x = x.split()
print "{0} = {1}".format(x[0],sum(map(int, x[1:])))
# output
['Year:', 'Dec:', 'Jan:']
1 = 110
2 = 75
3 = 60
4 = 60
5 = 20
Run Code Online (Sandbox Code Playgroud)
The*_*Cat 17
按列读取是否更难?
无论如何,这会读取该行并将值存储在列表中:
for line in open("csvfile.csv"):
csv_row = line.split() #returns a list ["1","50","60"]
Run Code Online (Sandbox Code Playgroud)
现代解决方案
# pip install pandas
import pandas as pd
df = pd.read_table("csvfile.csv", sep=" ")
Run Code Online (Sandbox Code Playgroud)
小智 6
最简单的方法是这样:
from csv import reader
# open file in read mode
with open('file.csv', 'r') as read_obj:
# pass the file object to reader() to get the reader object
csv_reader = reader(read_obj)
# Iterate over each row in the csv using reader object
for row in csv_reader:
# row variable is a list that represents a row in csv
print(row)
output:
['Year:', 'Dec:', 'Jan:']
['1', '50', '60']
['2', '25', '50']
['3', '30', '30']
['4', '40', '20']
['5', '10', '10']
Run Code Online (Sandbox Code Playgroud)
小智 5
import csv
with open('filepath/filename.csv', "rt", encoding='ascii') as infile:
read = csv.reader(infile)
for row in read :
print (row)
Run Code Online (Sandbox Code Playgroud)
这将解决您的问题.别忘了给出编码.