Converting file to key/value dictionary

前端 未结 2 497
借酒劲吻你
借酒劲吻你 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.

提交回复
热议问题