使用Python 2.7.13:
我试图从.txt文件中读取行,并从特定行更改一个字符。
该行本身看起来像这样:
过程X ~~~~~~~~~~~~~~~~~~~~~~ | N
我想转到字符串的最后一个字符(在本例中为N),最好在同一.txt文件中将其更改为“ Y”(如果可能,不希望创建其他文件)。
到目前为止,我的代码如下:
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 )
能请你帮我吗?
答案 0 :(得分:0)
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)
这应该为你做。