如何用Python将空格分隔文件转为制表符分隔并匹配fin.dat格式?
将shape.dat格式调整为与fin.dat一致的Python实现
以下是实现格式转换的Python脚本,可自动匹配fin.dat的行列格式:
# 获取fin.dat的每行列数 with open('fin.dat', 'r') as fin_file: # 跳过空行,读取第一行有效数据确定列数 target_cols = None for line in fin_file: cleaned_line = line.strip() if cleaned_line: target_cols = len(cleaned_line.split()) break # 读取shape.dat的所有数值 with open('shape.dat', 'r') as shape_file: all_values = [] for line in shape_file: val = line.strip() if val: all_values.append(val) # 按目标列数重新排版并写入新文件 with open('formatted_shape.dat', 'w') as output_file: for idx in range(0, len(all_values), target_cols): # 截取对应行数的数值,拼接成一行 line_values = all_values[idx:idx+target_cols] output_file.write(' '.join(line_values) + '\n')
关键说明
- 自动识别
fin.dat的每行列数,无需手动配置 - 自动跳过两个文件中的空行,避免无效数据干扰
- 转换后的文件保存为
formatted_shape.dat,格式与fin.dat完全对齐
内容的提问来源于stack exchange,提问作者hirak chatterjee
相关产品推荐
相关产品推荐

