指定文件格式

Posted weiliwei-lucky

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了指定文件格式相关的知识,希望对你有一定的参考价值。

指定文件格式

     # 读取文件,将文件的内容构造成指定格式的数据

  • 文件:wlw|123|23

    fsh|456|27

  • 格式:a.["wlw|123|23","fsh|456|27"]

    b.[["wlw","123","23"],["fsh","456","27"]]

    c.[“name":"wlw","pwd":"123","age":"23",

    “name":"fsh","pwd":"456","age":"23",

    ]

a.
v = []
with open(‘a.txt‘,mode=‘r‘,encoding=‘utf-8‘) as f:
   for i in f.readlines():
       v.append(i.strip())
print(v)
?
?
b.
v = []
with open(‘a.txt‘,mode=‘r‘,encoding=‘utf-8‘) as f:
   for i in f.readlines():
       v.append(i.strip().split(‘|‘))
print(v)
?
c.
v = []
with open(‘a.txt‘,mode=‘r‘,encoding=‘utf-8‘) as f:
   for i in f.readlines():
       dict =
       a,b,c = i.strip().split(‘|‘)
       dict[‘name‘] = a
       dict[‘pwd‘] = b
       dict[‘age‘] = c
       v.append(dict)
print(v)
?
?

大文件的操作

用readlines() 一行一行的读
with open(‘a.txt‘,mode=‘r‘,encoding=‘utf-8‘) as file:
   for data in file.readlines():
       print(data,end=" ")
?

以上是关于指定文件格式的主要内容,如果未能解决你的问题,请参考以下文章