标题: [问题求助] Python如何按列取出txt文件中的数据? [打印本页]
作者: Blakelee 时间: 2021-1-6 21:17 标题: Python如何按列取出txt文件中的数据?
本帖最后由 Blakelee 于 2021-10-28 14:17 编辑
求助,有一个数据文件格式(data.txt)如下,想按列取出数据:a=[600.00, 607.00, 614.00,......,684.00],dio=[0.38072, 0.37969,......,0.36806], ksp=[0.02269, 0.02270,......,0.02291], mu=[0.02519, 0.02519,......,0.02519], g=[0.37565, 0.37705,......,0.39272], ru=[0.00787, 0.00787,......,0.00787], ky=[ 0.04390, 0.04330,......,0.03659], 谢谢!
作者: cfwyy77_bat 时间: 2021-1-8 10:43
- file = "data.txt"
- g={}
-
- def main():
- local={"a": []}
- with open(file,"r",encoding="utf-8") as f:
- for line in f:
- row = line.strip('\n')[2:-3] #去回车及首尾多余{},
- if row:
- items = row.split('}, {')
- local["a"].append(float(items[0].split(',')[1])) #第1列
- for i in range(1,len(items)): #处理第2~8列
- item = items[i].split(',')
- key = item[0].strip('"')
- value = float(item[1])
- if key not in local:
- exec(f"{key}=[]",g,local)
- exec(f"{key}.append({value})",g,local)
-
- for k,v in local.items():
- print(f"{k} = {v}")
-
- if __name__ == "__main__":
- main()
复制代码
结果:- a = [600.0, 607.0, 614.0, 621.0, 628.0, 635.0, 642.0, 649.0, 656.0, 663.0, 670.0, 677.0, 684.0]
- dio = [0.38072, 0.37969, 0.37865, 0.37761, 0.37656, 0.3755, 0.37445, 0.37338, 0.37232, 0.37125, 0.37019, 0.36913, 0.36806]
- ksp = [0.02269, 0.0227, 0.02272, 0.02273, 0.02275, 0.02276, 0.02278, 0.0228, 0.02282, 0.02284, 0.02286, 0.02288, 0.02291]
- mu = [0.02519, 0.02519, 0.02519, 0.02519, 0.02519, 0.02519, 0.02519, 0.02519, 0.02519, 0.02519, 0.02519, 0.02519, 0.02519]
- g = [0.37565, 0.37705, 0.37846, 0.37988, 0.3813, 0.38272, 0.38415, 0.38558, 0.38701, 0.38844, 0.38987, 0.3913, 0.39272]
- ru = [0.00787, 0.00787, 0.00787, 0.00787, 0.00787, 0.00787, 0.00787, 0.00787, 0.00787, 0.00787, 0.00787, 0.00787, 0.00787]
- q = [0.14396, 0.14419, 0.14441, 0.14464, 0.14487, 0.14509, 0.14532, 0.14554, 0.14577, 0.14599, 0.14621, 0.14644, 0.14666]
- ky = [0.0439, 0.0433, 0.04269, 0.04208, 0.04147, 0.04086, 0.04024, 0.03963, 0.03902, 0.03841, 0.0378, 0.03719, 0.03659]
复制代码
作者: Blakelee 时间: 2021-1-8 13:28
回复 2# cfwyy77_bat
运行报错了
作者: cfwyy77_bat 时间: 2021-1-11 09:08
回复 3# Blakelee
格式和你给的例子文本可能不同。你先看明白了,再改改应该不难呀
作者: Blakelee 时间: 2021-1-12 00:01
好的,谢谢!
欢迎光临 批处理之家 (http://www.bathome.net/) |
Powered by Discuz! 7.2 |