하나 이상의 공통 열을 기반으로 여러 파일 (심지어> 2)을 병합하려면 파이썬에서 가장 효율적이고 효율적인 방법 중 하나는 "양조장"을 사용하는 것입니다. 병합을 위해 고려해야 할 필드와 저장해야 할 필드를 지정할 수도 있습니다.
import brewery
from brewery
import ds
import sys
sources = [
{"file": "grants_2008.csv",
"fields": ["receiver", "amount", "date"]},
{"file": "grants_2009.csv",
"fields": ["id", "receiver", "amount", "contract_number", "date"]},
{"file": "grants_2010.csv",
"fields": ["receiver", "subject", "requested_amount", "amount", "date"]}
]
모든 필드의 목록을 작성하고 소스 정의를 통해 데이터의 출처에 대한 정보를 저장하는 파일 이름을 records.Go 추가하고 필드 수집 :
for source in sources:
for field in source["fields"]:
if field not in all_fields:
out = ds.CSVDataTarget("merged.csv")
out.fields = brewery.FieldList(all_fields)
out.initialize()
for source in sources:
path = source["file"]
# Initialize data source: skip reading of headers
# use XLSDataSource for XLS files
# We ignore the fields in the header, because we have set-up fields
# previously. We need to skip the header row.
src = ds.CSVDataSource(path,read_header=False,skip_rows=1)
src.fields = ds.FieldList(source["fields"])
src.initialize()
for record in src.records():
# Add file reference into ouput - to know where the row comes from
record["file"] = path
out.append(record)
# Close the source stream
src.finalize()
cat merged.csv | brewery pipe pretty_printer
큰 일을 조인; 입력 파일은 키에서 정렬되어야합니다. 또한 임의의 csv 파일을 읽을 수 없습니다. 특히 인용 된 필드 내의 쉼표는 해당 레코드에 대한 모든 필드 넘버를 이동시킬 것입니다. – Javier
@Javier : 동의 했으므로 - 내 의견을 보지 않고도 내 대답을 업데이트 한 이유는 무엇입니까? 편집). –