栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

读取shoes.txt python dict、list、 string

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

读取shoes.txt python dict、list、 string

f = open('shoes.txt')
lines = f.read().splitlines()#不分行、[, , ,、、、,]读出来
print(lines)
title = ['brand', 'color', 'size']
rst = []
for line in lines:
    d = {}
    _line = line.split()
    for i in range(0, len(title)):
        d[title[i]] = _line[i]#dict :key-value
    print(d)
#方法二
# rst.append(d)
#print(rst)
def main():
    with open('shoes.txt','r') as f:
        lines = f.readlines()
        result = []
        for line in lines:
            words = line.strip().split(" ")#去掉前后空字符
            result.append({
                "brand":words[0],
                "color":words[-2],
                "size":words[-1]
            })
        print(result)
if __name__=="__main__":
    main()

#read() 每次读取整个文件,它通常用于将文件内容放到一个字符串变量中。如果文件大于可用内存,为了保险起见,可以反复调用read(size)方法,每次最多读取size个字节的内容。
#readlines() 之间的差异是后者一次读取整个文件,象 .read() 一样。.readlines() 自动将文件内容分析成一个行的列表,该列表可以由 Python 的 for … in … 结构进行处理。
#readline() 每次只读取一行,通常比readlines() 慢得多。仅当没有足够内存可以一次读取整个文件时,才应该使用 readline()。
https://blog.csdn.net/liuyhoo/article/details/80756812?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522164301747716780265478835%2522%252C%2522scm%2522%253A%252220140713.130102334…%2522%257D&request_id=164301747716780265478835&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2alltop_positive~default-1-80756812.first_rank_v2_pc_rank_v29&utm_term=readlines&spm=1018.2226.3001.4187

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/724865.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号