python读取python数据类型的文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wshzd/article/details/86090721

比如文件格式为

([{"feature":"产权","type":"n"}, {"feature":"清晰","type":"a"}],[{"feature":"大景城","type":"ns"}, {"feature":"精装","type":"b"}])
([{"feature":"位置","type":"n"}, {"feature":"市","type":"n"}],[{"feature":"毛坯房","type":"nz"}, {"feature":"三居室","type":"n"}])

如果使用open方式读取文件的话,返回的是str类型,但是文件明显有比较好的tuple、list、json格式,因此思路是怎么把文件的每一行在读取的过程中进行转换成原始的格式,而不是str类型,处理方式如下:

with open(file, 'r', encoding='utf8') as file_object:
    for line in file_object.readlines():
        if (len(line)) > 12:
            loc = locals()
            exec('b='+ line)
            print(loc['b'])

猜你喜欢

转载自blog.csdn.net/wshzd/article/details/86090721