我有一个包含约2000条记录的CSV文件。
每条记录都有一个字符串和一个类别。
This is the first line, Line1
This is the second line, Line2
This is the third line, Line3
我需要将此文件读入一个看起来像这样的列表;
List = [('This is the first line', 'Line1'),
('This is the second line', 'Line2'),
('This is the third line', 'Line3')]
如何使用Python将此csv
导入到我需要的列表中?
答案 0 :(得分:257)
使用csv
模块(Python 2.x):
import csv
with open('file.csv', 'rb') as f:
reader = csv.reader(f)
your_list = list(reader)
print your_list
# [['This is the first line', 'Line1'],
# ['This is the second line', 'Line2'],
# ['This is the third line', 'Line3']]
如果你需要元组:
import csv
with open('test.csv', 'rb') as f:
reader = csv.reader(f)
your_list = map(tuple, reader)
print your_list
# [('This is the first line', ' Line1'),
# ('This is the second line', ' Line2'),
# ('This is the third line', ' Line3')]
Python 3.x版本(由@seokhoonlee在下面)
import csv
with open('file.csv', 'r') as f:
reader = csv.reader(f)
your_list = list(reader)
print(your_list)
# [['This is the first line', 'Line1'],
# ['This is the second line', 'Line2'],
# ['This is the third line', 'Line3']]
答案 1 :(得分:42)
更新 Python3 :
import csv
with open('file.csv', 'r') as f:
reader = csv.reader(f)
your_list = list(reader)
print(your_list)
# [['This is the first line', 'Line1'],
# ['This is the second line', 'Line2'],
# ['This is the third line', 'Line3']]
答案 2 :(得分:35)
Pandas非常善于处理数据。以下是如何使用它的一个示例:
import pandas as pd
# Read the CSV into a pandas data frame (df)
# With a df you can do many things
# most important: visualize data with Seaborn
df = pd.read_csv('filename.csv', delimiter=',')
# Or export it in many ways, e.g. a list of tuples
tuples = [tuple(x) for x in df.values]
# or export it as a list of dicts
dicts = df.to_dict().values()
一个很大的优势是pandas自动处理标题行。
如果您还没有听说过Seaborn,我建议您查看它。
另请参阅:How do I read and write CSV files with Python?
<2>熊猫#2import pandas as pd
# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()
# Convert
dicts = df.to_dict('records')
df的内容是:
country population population_time EUR
0 Germany 82521653.0 2016-12-01 True
1 France 66991000.0 2017-01-01 True
2 Indonesia 255461700.0 2017-01-01 False
3 Ireland 4761865.0 NaT True
4 Spain 46549045.0 2017-06-01 True
5 Vatican NaN NaT True
dicts的内容是
[{'country': 'Germany', 'population': 82521653.0, 'population_time': Timestamp('2016-12-01 00:00:00'), 'EUR': True},
{'country': 'France', 'population': 66991000.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': True},
{'country': 'Indonesia', 'population': 255461700.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': False},
{'country': 'Ireland', 'population': 4761865.0, 'population_time': NaT, 'EUR': True},
{'country': 'Spain', 'population': 46549045.0, 'population_time': Timestamp('2017-06-01 00:00:00'), 'EUR': True},
{'country': 'Vatican', 'population': nan, 'population_time': NaT, 'EUR': True}]
<2>熊猫#3
import pandas as pd
# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()
# Convert
tuples = [[row[col] for col in df.columns] for row in df.to_dict('records')]
tuples
的内容是:
[['Germany', 82521653.0, Timestamp('2016-12-01 00:00:00'), True],
['France', 66991000.0, Timestamp('2017-01-01 00:00:00'), True],
['Indonesia', 255461700.0, Timestamp('2017-01-01 00:00:00'), False],
['Ireland', 4761865.0, NaT, True],
['Spain', 46549045.0, Timestamp('2017-06-01 00:00:00'), True],
['Vatican', nan, NaT, True]]
答案 3 :(得分:5)
如果您确定输入中没有逗号,除了将类别分开外,您可以在,
上read the file line by line和split,然后将结果推送到{{1 }}
也就是说,看起来您正在查看CSV文件,因此您可以考虑使用the modules
答案 4 :(得分:5)
import csv
from pprint import pprint
with open('text.csv', newline='') as file:
reader = csv.reader(file)
l = list(map(tuple, reader))
pprint(l)
[('This is the first line', ' Line1'),
('This is the second line', ' Line2'),
('This is the third line', ' Line3')]
如果csvfile是文件对象,则应使用newline=''
打开它
csv module
答案 5 :(得分:4)
result = []
for line in text.splitlines():
result.append(tuple(line.split(",")))
答案 6 :(得分:2)
如上所述,您可以在python中使用csv
库。 csv表示逗号分隔值,这似乎与您的情况完全相同:标签和用逗号分隔的值。
作为类别和值类型,我宁愿使用字典类型而不是元组列表。
无论如何,在下面的代码中,我展示了两种方式:d
是字典,l
是元组列表。
import csv
file_name = "test.txt"
try:
csvfile = open(file_name, 'rt')
except:
print("File not found")
csvReader = csv.reader(csvfile, delimiter=",")
d = dict()
l = list()
for row in csvReader:
d[row[1]] = row[0]
l.append((row[0], row[1]))
print(d)
print(l)
答案 7 :(得分:1)
一个简单的循环就足够了:
lines = []
with open('test.txt', 'r') as f:
for line in f.readlines():
l,name = line.strip().split(',')
lines.append((l,name))
print lines
答案 8 :(得分:1)
稍微扩展您的要求并假设您不关心行的顺序并希望将它们分类在类别下,以下解决方案可能适合您:
>>> fname = "lines.txt"
>>> from collections import defaultdict
>>> dct = defaultdict(list)
>>> with open(fname) as f:
... for line in f:
... text, cat = line.rstrip("\n").split(",", 1)
... dct[cat].append(text)
...
>>> dct
defaultdict(<type 'list'>, {' CatA': ['This is the first line', 'This is the another line'], ' CatC': ['This is the third line'], ' CatB': ['This is the second line', 'This is the last line']})
通过这种方式,您可以在字典下的所有相关行中获得关键字作为类别。
答案 9 :(得分:1)
这是Python 3.x中最简单的将CSV导入多维数组的方法,它仅4行代码而无需导入任何内容!
#pull a CSV into a multidimensional array in 4 lines!
L=[] #Create an empty list for the main array
for line in open('log.txt'): #Open the file and read all the lines
x=line.rstrip() #Strip the \n from each line
L.append(x.split(',')) #Split each line into a list and add it to the
#Multidimensional array
print(L)
答案 10 :(得分:1)
不幸的是,我发现没有一个现有的答案特别令人满意。
这是使用csv模块的简单,完整的Python 3解决方案。
import csv
with open('../resources/temp_in.csv', newline='') as f:
reader = csv.reader(f, skipinitialspace=True)
rows = list(reader)
print(rows)
注意skipinitialspace=True
参数。这很必要,因为不幸的是,OP的CSV在每个逗号后都包含空格。
输出:
[['This is the first line', 'Line1'], ['This is the second line', 'Line2'], ['This is the third line', 'Line3']]
答案 11 :(得分:0)
Next is a piece of code which uses csv module but extracts file.csv contents to a list of dicts using the first line which is a header of csv table
import csv
def csv2dicts(filename):
with open(filename, 'rb') as f:
reader = csv.reader(f)
lines = list(reader)
if len(lines) < 2: return None
names = lines[0]
if len(names) < 1: return None
dicts = []
for values in lines[1:]:
if len(values) != len(names): return None
d = {}
for i,_ in enumerate(names):
d[names[i]] = values[i]
dicts.append(d)
return dicts
return None
if __name__ == '__main__':
your_list = csv2dicts('file.csv')
print your_list
答案 12 :(得分:0)
您可以使用list()
函数将csv阅读器对象转换为列表
import csv
with open('input.csv') as csv_file:
reader = csv.reader(csv_file, delimiter=',')
rows = list(reader)
print(rows)