解决不同长度数组作为列写入.txt文件时的截断问题
问题描述
我正在解析模拟数据,希望将所有数据写入单个.txt文件。现有4个数组,其中recoil、energy、depth三个数组长度约140000,而Ni_recoil数组长度约90000。使用现有代码写入文件时,内容会被截断至最短数组(Ni_recoil)的长度,我需要生成包含全部4列数据且不截断长数组的.txt文件。
当前输出(简化示例)
Ni_recoil = [1,2,3] recoil = [1,2,3,4,5] Energy = [1,2,3,4,5] depth = [1,2,3,4,5] Output: 1 1 1 1 2 2 2 2 3 3 3 3
期望输出(简化示例)
Output: 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 5 5 5
当前代码
path=r"C:\Users\Jorge\Desktop\Uni\Research\JANUS\IIEE\Results\StainlessSteel_Xenon" name_of_file = input("What is the name of the file: ") completeName = os.path.join(path, name_of_file+".txt") data=zip(Ni_recoil, recoil, energy, depth) with open(completeName, 'w') as file: for(Ni_recoil, recoil, energy, depth) in data: file.write("{0},{1},{2},{3}\n".format(Ni_recoil, recoil, energy, depth))
解决方案
问题出在zip()函数上——它只会迭代到最短数组的长度,长数组超出部分的元素会被直接丢弃。要实现遍历所有数组的全部元素,改用itertools.zip_longest()即可,它会迭代到最长数组的长度,对于短数组中缺失的元素,你可以自定义填充值(比如空字符串)。
修改后的代码
import os from itertools import zip_longest path=r"C:\Users\Jorge\Desktop\Uni\Research\JANUS\IIEE\Results\StainlessSteel_Xenon" name_of_file = input("What is the name of the file: ") completeName = os.path.join(path, name_of_file+".txt") # 使用zip_longest,fillvalue指定缺失位置的填充内容,这里用空字符串 data = zip_longest(Ni_recoil, recoil, energy, depth, fillvalue="") with open(completeName, 'w') as file: for ni_r, r, e, d in data: # 按逗号分隔输出,缺失位置留空 file.write("{0},{1},{2},{3}\n".format(ni_r, r, e, d))
对齐格式调整(可选)
如果想要和期望示例一样用空格分隔并对齐,可以修改格式化字符串:
with open(completeName, 'w') as file: for ni_r, r, e, d in data: # 左对齐,每列占4个字符宽度,缺失位置留空 file.write("{:<4}{:<4}{:<4}{:<4}\n".format(ni_r or "", r, e, d))
这样处理后,长数组的所有元素都会被写入文件,短数组缺失的位置会用指定填充值代替,完全符合你的需求。
内容的提问来源于stack exchange,提问作者JORGE FERNANDEZ-COPPEL VELASCO
相关产品推荐
相关产品推荐

