python - 向固定宽度文本文件添加分隔符

标签 python

我正在尝试向固定宽度的文本文件添加分隔符。

这是我迄今为止所拥有的:

list=[4,29,36,45,70,95,100,111,115,140,150,151,152,153,169]
with open('output.txt', 'w') as outfile:
    with open('input.txt', 'r') as infile:
        for line in infile:
            newline = line[:4] + '|' + line[4:]
            outfile.write(newline)
outfile.close()

上面的代码在第 5 个字节处插入一个管道。我现在想在列表中的下一个值处添加一个管道 (29)。我使用的是 Python 2.7。

最佳答案

我认为这就是您想要做的:

list=[4,29,36,45,70,95,100,111,115,140,150,151,152,153,169]
with open('output.txt', 'w') as outfile:
    with open('results.txt', 'r') as infile:
        for line in infile:
            iter = 0
            prev_position = 0
            position = list[iter]
            temp = []
            while position < len(line) and iter + 1 < len(list):
                iter += 1
                temp.append(line[prev_position:position])
                prev_position = position
                position = list[iter]
            temp.append(line[prev_position:])

            temp_str = ''.join(x + "|" for x in temp)
            temp_str = temp_str[:-1]

            outfile.write(temp_str)

这需要一个输入文件并在列表中的位置插入一个|。这将处理小于或大于列表中的值的情况。

关于python - 向固定宽度文本文件添加分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26745405/

相关文章:

python - 如何查看 Jupyter Notebook 中调用我的方法或类的所有行的列表?

python - 由于 g++ 编译器错误,NS-3 构建失败

python - 找不到资源错误: When Reading CSV from Azure Blob using Pandas with its SAS URL

python - 用python读取 float

python - 如何让 pynput 与 ubuntu 一起工作?

python - 跨类的多个实例的一个 session

python - 在 python 中查找字符串中存在的相似文本

python - 在字典 switch 语句中模拟 'else'

python - 如何将 pandas DataFrame 表保存为 png

python - 在 Windows 中将 EOF 发送到 PyCharm 控制台