如何在python中将列添加到现有的文本文件中?

2024-04-26 13:14:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我用python创建了一个文本文件,现在我想添加一个具有相同行长度的第6列,重复如下内容:

red
blue
yellow
green
red
blue
yellow
green
... to the end of the file

我的原始文件是这样的

^{pr2}$

我希望它看起来像这样

rtlvis_20190518_13.35.48_00087.bin 29.596454073622454 264.8326389532491 29.596454073622454 264.8326389532491  red
rtlvis_20190518_13.35.48_00056.bin 29.596454073622454 264.8326389532491 29.596454073622454 264.8326389532491  blue
rtlvis_20190518_13.35.48_00117.bin 29.596454073622454 264.8326389532491 29.596454073622454 264.8326389532491  green
rtlvis_20190518_13.35.48_00102.bin 29.596454073622454 264.8326389532491 29.596454073622454 264.8326389532491  yellow
rtlvis_20190518_13.35.48_00088.bin 29.596454073622454 264.8326389532491 29.596454073622454 264.8326389532491  red
rtlvis_20190518_13.35.48_00043.bin 29.596454073622454 264.8326389532491 29.596454073622454 264.8326389532491  green
rtlvis_20190518_13.35.48_00131.bin 29.596454073622454 264.8326389532491 29.596454073622454 264.8326389532491  blue

Tags: 文件oftheto内容bingreenblue
2条回答

您要查找的基本概念是模运算符“%”。 https://docs.python.org/3.3/reference/expressions.html#binary-arithmetic-operations

colors = ['red','blue','yellow','green']
with open('file.txt') as f:
    for lineno, line in enumerate(f):
        color = colors[lineno % len(colors)]
        print(line.rstrip() + ' ' + color)

EDIT:写入文件而不是STDOUT的较大示例:

^{pr2}$

您应该逐行迭代输入文件,并尝试为其添加适当的颜色。有关详细信息,请查看下面的片段。在

colors = ['red', 'blue', 'yellow', 'green']
with open('input.txt') as input_file, open('output.txt', 'w') as output_file:
    for i, line in enumerate(input_file):
        color = colors[i % len(colors)]
        new_line = '{} {}\n'.format(line.rstrip(), color)
        output_file.write(line)

还有另一种解决方案可以提高功能。让我们检查一下!在

^{pr2}$

相关问题 更多 >