簡體   English   中英

從文本文件的Python字典

[英]Python Dictionary from text file

您好我有一個文件文本,其中包含如下序列:

TCA:DateIn,TimeIn,Content,Quantity,Company,TankerName,Country,PortFrom  
26/02/2013,15:00,Natural gas,30000,Linkers, Blue Ice, China,Shanghai
09/03/2013,06:30,Sugar,45000,Navigators,Lady Fish, Netherlands, Rotterdam 

我如何使用字典,標題名稱作為鍵(DateIn,TimeIn ...),值下方的行顯示為這樣的類,其中列由制表符而不是逗號分隔:

TCA:TankerName Company      Country     DateIn        TimeIn     PortFrom     Content      Quantity
Blue Ice       Linkers      China       26/02/2013    15:00      Shanghai     NaturalGas   30000
Lady Fish      Navigators   Netherlands 09/03/2013    06:30      Rotterdam    Sugar        45000

我嘗試了很多東西,但我不能解決的問題是我無法將鍵與值相關聯。 我目前正在使用python 3.3.1,但如果它使用另一個版本沒有問題

謝謝

這將讓你開始:

import csv

with open('/tmp/ships.csv','r') as din:
    scsv=csv.reader(din)
    for i,row in enumerate(scsv):
        if i:
            for type,data in zip(header,row):
                d[type].append(data.strip())
        else:
            header=row
            d={item:[] for item in row}

print(d)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM