[英]Python: How to write dictionary to csv file when one key has multiple values, each key is a new row, but each value is a new column?
[英]How to parse a csv with python, when one column has multiple lines
我有一個 csv 文件,它是“名稱、地點、事物”。 thing 列通常有“word\nanotherword\nanotherword\n” 我試圖弄清楚如何將其解析為單獨的行而不是單個列中的多行條目。 IE
name, place, word
name, place, anotherword
name, place, anotherword
我確信這很簡單,但我很難理解我需要做什么。
用以下column_wrapper
包裝您的csv閱讀器:
def column_wrapper(reader):
for name, place, thing in reader:
for split_thing in thing.strip().split('\n'):
yield name, place, split_thing
而且你會變得很黃金。
無需研究代碼,本質上您想要做的就是檢查“事物”中是否有換行符。 如果有,則需要在換行符上將它們分割。 這將為您提供令牌列表(“事物”中的行),並且由於這本質上是一個內部循環,因此您可以使用原始name
和place
以及新的thing_token
。 生成器功能非常適合於此。
這使我想到了克魯羅克。 但是,kroolik的答案中有一個小錯誤:
如果要使用column_wrapper
生成器,則需要考慮以下事實:csv閱讀器在換行符中轉義了反斜杠,因此它們看起來像\\\\n
而不是\\n
。 另外,您需要檢查空白的“東西”。
def column_wrapper(reader):
for name, place, thing in reader:
for split_thing in thing.strip().split('\\n'):
if split_thing:
yield name, place, split_thing
然后,您可以獲取像這樣的數據:
with open('filewithdata.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
data = [[data, name, thing] for data, name, thing in column_wrapper(reader)]
或(無column_wrapper
):
data = []
with open('filewithdata.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
name, place, thing = tuple(row)
if '\\n' in thing:
for item in thing.split('\\n'):
if item != '\n':
data.append([name, place, item)]
我建議使用column_wrapper
因為生成器更加通用和Pythonic。
確保將import csv
添加到文件頂部(盡管我確定您已經知道)。 希望有幫助!
您總是可以逐行讀取文件
#! /usr/bin/env python2.7.2
file = open("demo.csv", "r+");
for line in file:
line = line.replace(",", " ")
words = line.split()
print(words[0])
print(words[1])
print(words[2])
file.close()
假設文件內容是
name1,place1,word1
name2,place2,anotherword2
name3,place3,anotherword3
如果有人遇到我遇到的同樣問題。 如果您的單元格中有多行字符串,請使用此答案中指定的 quotechar 字段:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.