【发布时间】:2020-11-15 10:08:35
【问题描述】:
我有多个 txt 文件,每个 txt 文件都有 6 列。我想要做的:只添加一列作为最后一列,所以最后 txt 文件最多有 7 列,如果 我再次运行脚本它不应该添加一个新的一个:
每个文件开头有六列:
637.39 718.53 155.23 -0.51369 -0.18539 0.057838 3.209840789730089
636.56 720 155.57 -0.51566 -0.18487 0.056735 3.3520643559939938
635.72 721.52 155.95 -0.51933 -0.18496 0.056504 3.4997850701290125
我想要的是仅当当前列数为 6 时才添加一个新的零列,之后它应该防止在我再次运行脚本时添加新列(7 列是最后一列的总数是零):
637.39 718.53 155.23 -0.51369 -0.18539 0.057838 3.209840789730089 0
636.56 720 155.57 -0.51566 -0.18487 0.056735 3.3520643559939938 0
635.72 721.52 155.95 -0.51933 -0.18496 0.056504 3.4997850701290125 0
我的代码有效,每次运行脚本时都会添加一个额外的列,但我只想在列数为 6 时添加一次。其中 (a) 给我列数,如果满足条件,然后添加新的:
from glob import glob
import numpy as np
new_column = [0] * 20
def get_new_line(t):
l, c = t
return '{} {}\n'.format(l.rstrip(), c)
def writecolumn(filepath):
# Load data from file
with open(filepath) as datafile:
lines = datafile.readlines()
a=np.loadtxt(lines, dtype='str').shape[1]
print(a)
**#if a==6: (here is the problem)**
n, r = divmod(len(lines), len(new_column))
column = new_column * n + new_column[:r]
new_lines = list(map(get_new_line, zip(lines, column)))
with open(filepath, "w") as f:
f.writelines(new_lines)
if __name__ == "__main__":
filepaths = glob("/home/experiment/*.txt")
for path in filepaths:
writecolumn(path)
当我检查列数 #if a==6 并在 if 语句中移动内容时出现错误。如果一切正常,并且每次运行时仍然添加一列,则无需在其中移动内容。 任何帮助表示赞赏。
要测试代码,请创建两个/一个包含六列随机数的 txt 文件。
【问题讨论】:
标签: python python-3.x python-2.7 python-requests