首页 文章

从python中的行中删除引号

提问于
浏览
2

我有一个具有相同数据的文件:

{'name': 'Atucha', 'location': (-34.0, -59.167), 'active_reactors': 1},
    {'name': 'Embalse', 'location': (-32.2333, -64.4333), 'active_reactors': 1},
    {'name': 'Armenia', 'location': (40.167, 44.133), 'active_reactors': 1},
    {'name': 'Br', 'location': (51.217, 5.083), 'active_reactors': 1},
    {'name': 'Doel', 'location': (51.333, 4.25), 'active_reactors': 4},
    {'name': 'Tihange', 'location': (50.517, 5.283), 'active_reactors': 3}

我试着读:

import csv
listok=[]
with open('Uni_coord.csv', 'r') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        listok.extend(row)

但是在这一步之后,我在列表对象的所有行之前和之后都看到了非常奇怪的引号:

["{'name': '', 'location': (), 'NAME': '')}"] .

期望的输出看起来像一个简单的列表对象,每行没有引号:

[{'name': 'Atucha', 'location': (-34.0, -59.167), 'active_reactors': 1},
    {'name': 'Embalse', 'location': (-32.2333, -64.4333), 'active_reactors': 1},
    {'name': 'Armenia', 'location': (40.167, 44.133), 'active_reactors': 1},
    {'name': 'Br', 'location': (51.217, 5.083), 'active_reactors': 1},
    {'name': 'Doel', 'location': (51.333, 4.25), 'active_reactors': 4},
    {'name': 'Tihange', 'location': (50.517, 5.283), 'active_reactors': 3}]

如何在文件中删除它或更正确地读取数据?谢谢!

1 回答

  • 1

    @Janek ,您可以在阅读 Uni_coord.csv 后尝试以下代码获取词典列表 .

    注意:您的Uni_coord.csv文件不包含实际CSV文件应包含的格式的数据,但您仍可以读取普通文件 . 问题是你不必在这里使用csv模块 .

    import json
    
    lines =""
    with open("Uni_coord.csv") as f:
        for line in f.readlines():
            lines += line.strip()
    
    lines +=  "[" + lines + "]"
    my_list = json.loads(lines)
    
    print(l)
    
    # Pretty printing list of dictionaries (it is useful to view the contents of huge list)
    print(json.dumps(my_list, indent=4))
    

相关问题