Python 导入 csv 到列表[重复]
- 2024-12-12 08:40:00
- admin 原创
- 165
问题描述:
我有一个包含大约 2000 条记录的 CSV 文件。
每条记录都有一个字符串和一个类别:
This is the first line,Line1
This is the second line,Line2
This is the third line,Line3
我需要将此文件读入如下列表:
data = [('This is the first line', 'Line1'),
('This is the second line', 'Line2'),
('This is the third line', 'Line3')]
如何使用 Python 将此 CSV 导入到我需要的列表中?
解决方案 1:
使用csv 模块:
import csv
with open('file.csv', newline='') as f:
reader = csv.reader(f)
data = list(reader)
print(data)
输出:
[['This is the first line', 'Line1'], ['This is the second line', 'Line2'], ['This is the third line', 'Line3']]
如果需要元组:
import csv
with open('file.csv', newline='') as f:
reader = csv.reader(f)
data = [tuple(row) for row in reader]
print(data)
输出:
[('This is the first line', 'Line1'), ('This is the second line', 'Line2'), ('This is the third line', 'Line3')]
旧的 Python 2 答案,也使用csv
模块:
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']]
解决方案 2:
针对Python 3进行了更新:
import csv
with open('file.csv', newline='') 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']]
解决方案 3:
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,我建议你看一下。
另请参阅:如何使用 Python 读取和写入 CSV 文件?
熊猫#2
import 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
字典的内容是
[{'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}]
熊猫#3
import pandas as pd
# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()
# Convert
lists = [[row[col] for col in df.columns] for row in df.to_dict('records')]
的内容lists
为:
[['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]]
解决方案 4:
Python3 的更新:
import csv
from pprint import pprint
with open('text.csv', newline='') as file:
reader = csv.reader(file)
res = list(map(tuple, reader))
pprint(res)
输出:
[('This is the first line', ' Line1'),
('This is the second line', ' Line2'),
('This is the third line', ' Line3')]
如果 csvfile 是文件对象,则应使用newline=''
.csv
模块打开
解决方案 5:
如果你确定输入中没有逗号(除了分隔类别之外),则可以逐行读取文件并在 上进行拆分,
,然后将结果推送到List
也就是说,看起来你正在查看一个 CSV 文件,因此你可以考虑使用它的模块
解决方案 6:
result = []
for line in text.splitlines():
result.append(tuple(line.split(",")))
解决方案 7:
您可以使用该list()
函数将 csv 阅读器对象转换为列表
import csv
with open('input.csv', newline='') as csv_file:
reader = csv.reader(csv_file, delimiter=',')
rows = list(reader)
print(rows)
解决方案 8:
一个简单的循环就足够了:
lines = []
with open('test.txt', 'r') as f:
for line in f.readlines():
l,name = line.strip().split(',')
lines.append((l,name))
print lines
解决方案 9:
正如评论中所说,您可以使用csv
python 中的库。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)
解决方案 10:
不幸的是,我发现现有的答案都不能令人满意。
这是一个简单而完整的 Python 3 解决方案,使用csv模块。
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:
稍微扩展您的要求并假设您不关心行的顺序并希望将它们分组到类别下,则以下解决方案可能适合您:
>>> fname = "lines.txt"
>>> from collections import defaultdict
>>> dct = defaultdict(list)
>>> with open(fname) as f:
... for line in f:
... text, cat = line.rstrip("
").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']})
这样,您便可以获得字典中以该类别为键的所有相关行。
解决方案 12:
这是在 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
from each line
L.append(x.split(',')) #Split each line into a list and add it to the
#Multidimensional array
print(L)
解决方案 13:
接下来是一段使用 csv 模块的代码,但使用第一行(即 csv 表的标题)将 file.csv 内容提取到字典列表中
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