我在用python编写的.csv文件中遇到错误(这是必需的格式,因为我所在的团队依赖于.csv)。以非模式化的方式,在数百个1g文件中会出现错误。例如,只有1行的额外10列,有固定输入的额外行,某些行缺少~10列。我重新运行了两次相同的脚本,第二次运行时没有出现错误。我需要一种方法来确保这些文件被正确地写入。下面是我正在使用的代码(我知道它不是最有效的,但我知道如何用这种方式来实现,我想把我是如何做到这一点的)。在# Sample inputs, representative of the actual data I'm working with.
output = np.zeros([40000, 1000]) # for example
iso3 = 'ALB'
sex = 'M'
year = np.ones(40000)
post_env = np.repeat(10, 40000)
post_cause = np.repeat('a', 40000)
post_pop = np.repeat(100, 40000)
outsheet = np.zeros([output.shape[0], output.shape[1]+7], dtype='|S20')
outsheet[:, 0] = iso3
outsheet[:, 1] = sex
outsheet[:, 2] = np.array(post_year, dtype='|S20')
outsheet[:, 3] = np.array(post_age, dtype='|S20')
outsheet[:, 4] = np.array(post_cause, dtype='|S20')
outsheet[:, 5] = np.array(post_env, dtype='|S20')
outsheet[:, 6] = np.array(post_pop, dtype='|S20')
outsheet[:, 7:] = np.array(output, dtype='|S20')
outsheet[outsheet=='nan'] = '.'
first_row = ['draw' + str(i) for i in range(output.shape[1])]
first_row.insert(0, 'population')
first_row.insert(0, 'envelope')
first_row.insert(0, 'cause')
first_row.insert(0, 'age')
first_row.insert(0, 'year')
first_row.insert(0, 'sex')
first_row.insert(0, 'iso3')
outfile = open('filename', 'w')
writer = csv.writer(outfile)
writer.writerow(first_row)
writer.writerows(outsheet)
outfile.close()
错误甚至包括第一列中的随机数值(应该都是'ALB')、一组额外的观察行和一个观察缺失的列(写后)。在