如何在txt文件Python中更改特定列的行值?

2024-04-26 22:29:05 发布

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

我有一个文本文件,有1列不同的值(浮点和整数),我想根据它的行更改一个值。我的代码是这样的:但是我知道应该替换什么值,如何按照行来做?在

with open('table1.txt', 'r+') as file:
    text = file.read()
    i = text.index('3.6') # 3.6 = old value
    file.seek(0)
    file.write(text[:i] + '7.84' + text[i + len('3.6'):]) # 7.84 = new value

其次,当我的文件中有多个列时,如何选择一行?例如,第2列第1行?塔克斯


Tags: 代码texttxtreadindexvalueaswith
1条回答
网友
1楼 · 发布于 2024-04-26 22:29:05

如果文件中的列按空间拆分:

def change_value(column, row, new_value):
    lines = []
    with open('table1.txt', 'r+') as file:
        for line in file:
            lines.append(line.rstrip().split())

        lines[row - 1][column - 1] = str(new_value)
        file.seek(0)
        for line in lines:
            line[-1] += "\n"    # or "\r\n" on windows
            file.write(' '.join(line))


change_value(2, 1, 7.84)

相关问题 更多 >