提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
前言
使用python语言处理数值的输出
一、对文本中的数值固定输出长度
将所有数值都固定到8个字符,不足8个字符的使用0填充,超过8个字符的使用科学计数法。
二、python脚本
1.分析脚本
代码如下:
result = []
with open ("test.txt",'r') as testfile:
next(testfile) #### 去除第一行表头
for line in testfile:
line = line.rstrip().split('\t') ## 去除末尾的换行符,以Tab分隔
# line = line.rstrip().split(',') ## 去除末尾的换行符,以","分隔
exact = [] # 新建空列表,存储修改格式后的数值
for value in line: # 循环每行的数值
num = float(value) # 转为浮点数
if num == 0: # 为 0 时需要单独列出来“:<12” 设置数值的宽度
exact.append(f'{"0.000000":<12}')
# 部分科学计数法的数值需要转为浮点数再计算字符长度,超过8字符转为浮点数
elif len(f'{num:.12f}'.rstrip('0')) > 8:
# 当科学计数法格式长度为8时,需要保留1,2,3位小数
if len(str(f'{num:.2e}')) == 8:
num = f'{num:.2e}'
exact.append(f'{num:<12}')
elif len(str(f'{num:.1e}')) == 8:
num = f'{num:.1e}'
exact.append(f'{num:<12}')
else:
num = f'{num:.3e}'
exact.append(f'{num:<12}')
# 长度不足8的进行补齐,整数的话会添加小数点
else:
num_str = f"{num:.8f}".rstrip('0')
while len(num_str) < 8:
num_str += '0'
exact.append(f'{num_str:<12}')
# 输出结果保存在result 列表中
result.append(f'{"FORCE":<12}'+f'{line[0]:<12}'+f'{line[1]:<12}'+''.join(exact[2:6])+'\n')
# 输出到屏幕
# print(f'{"FORCE":<12}'+f'{line[0]:<12}'+f'{line[1]:<12}'+''.join(exact[2:6]))
# 保存至文件
with open('out.txt','w') as outfile:
outfile.writelines(result)
2.使用输入数据示例
输入文件如下(示例):

总结
使用format函数将输入文件的第三,四,五,六列数值固定为8个字符,长度固定为12个字符,输出等宽的文件。