약 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')]
이 CSV를 Python을 사용하여 필요한 목록으로 가져 오려면 어떻게해야합니까?
답변
은 Using 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']]
답변
파이썬 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']]
답변
팬더 는 데이터 처리에 능숙합니다. 사용 방법의 예는 다음과 같습니다.
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()
한 가지 큰 장점은 팬더가 헤더 행을 자동으로 처리한다는 것입니다.
Seaborn에 대해 들어 본 적이 없다면 자세히 살펴 보는 것이 좋습니다.
파이썬으로 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
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}]
팬더 # 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]]
답변
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 모듈
답변
당신이 확실 귀하의 의견에는 쉼표, 카테고리를 분리하는 것보다 다른이없는 경우, 당신은 수있는 라인으로 파일 라인을 읽기 및 분할 에 ,
, 다음에 그 결과를 밀어List
즉, CSV 파일을보고있는 것처럼 사용하는 것이 좋습니다 그래서, 보이는 말했다 모듈을 그것을 위해
답변
result = []
for line in text.splitlines():
result.append(tuple(line.split(",")))
답변
주석에서 이미 말했듯이 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)
