Converting file to key/value dictionary

前端 未结 2 466
借酒劲吻你
借酒劲吻你 2021-01-28 09:18

I am unsure if what I have is actually creating a new dictionary. I want to take a file that currently has two words separated by commas on each line and turn it into a dictiona

相关标签:
2条回答
  • 2021-01-28 10:06

    Use the CSV module

    import csv
    with open('some.csv', 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
            print row
    

    They already solved the problem you are trying to solve, including quoting issues, iterating over lines, and parsing it out :)

    You can try something like this for your code:

    import csv
    def readACSV():
        with open('file.csv', 'r') as WDictionary
        reader = csv.reader(WDictionary)
        for row in reader:
             yield row
    
    for line in readACSV():
        print line
    

    Dont know if that helps, but a little usage example in case you were unsure how to use it.

    0 讨论(0)
  • 2021-01-28 10:09
    dict(line.split(',') for line in WDictionary)
    

    Edit: as suggested

    dict(line.strip().split(',') for line in WDictionary)
    
    0 讨论(0)
提交回复
热议问题