Импорт csv на Python в список
У меня есть файл CSV с около 2000 записей.
Каждая запись имеет строку и категорию для нее.
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')]
Как импортировать этот csv
в список, который мне нужен, используя Python?
Ответы
Ответ 1
Используйте 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(by @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']]
Ответ 2
Обновление для 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']]
Ответ 3
Панды очень хорошо справляются с данными. Вот один пример, как его использовать:
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, я рекомендую взглянуть на него.
См. также: Как читать и писать файлы CSV с помощью Python?
Панды № 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
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]]
Ответ 4
Обновление для Python3:
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
Ответ 5
Если вы уверены, что на вашем входе нет запятых, кроме как отделить категорию, вы можете читать файл по строкам и split на ,
, затем нажмите результат на List
Тем не менее, похоже, что вы смотрите на файл CSV, поэтому вы можете использовать модули для него
Ответ 6
result = []
for line in text.splitlines():
result.append(tuple(line.split(",")))
Ответ 7
Как уже было сказано в комментариях, вы можете использовать библиотеку 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)
Ответ 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
Несколько увеличив ваши требования и предполагая, что вам не нужно упорядочивать строки и вы хотите, чтобы они были сгруппированы по категориям, для вас может работать следующее решение:
>>> 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']})
Таким образом, вы получаете все соответствующие строки, доступные в словаре под ключом, являющимся категорией.
Ответ 10
Вот самый простой способ в 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)
Ответ 11
Далее приведен фрагмент кода, который использует модуль csv, но извлекает содержимое file.csv в список dicts, используя первую строку, которая является заголовком таблицы 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