从 .txt 文件中的字符串更改特定行中的字符

Changing a character in a particular line from a string within a .txt file

与 Python 2.7.13:

我正在尝试从 .txt 文件中读取行并更改特定行中的一个字符。

该行本身看起来像这样:

程序X~~~~~~~~~~~~~~~~~~~~~~~|N

我想从字符串转到最后一个字符(在本例中为 N)并将其更改为 'Y',最好是在同一个 .txt 文件中(如果可能,不需要创建额外的文件) .

到目前为止,我的代码如下所示:

with open('data.txt', 'r') as file:
    data = file.readlines()

#This is the second line of the .txt file and the chr is in the position 48 of the string
print data[1][48]

string = data[1][48].replace('N','Y')

data[1] = string

with open('data.txt', 'w') as file:
    file.writelines( data )

你能帮帮我吗?

with open('data.txt', 'r') as file:
    data = file.readlines()

LINE = 0
COLUMN = 2
CHARACTER = 'Z'

d = list(data[LINE])
d[COLUMN] = CHARACTER
data[LINE] = "".join(d)

with open('data.txt', 'w') as file:
    file.writelines(data)

这应该可以为您完成。