简体   繁体   中英

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

with Python 2.7.13:

I am trying to read the lines from a.txt file and changing one character from a particular line.

the line itself looks something like this:

ProcedureX~~~~~~~~~~~~~~~~~~~~~~~|N

I would like to go to the last character (in this case N) from the string and change it to 'Y' preferrably on the same.txt file (creating an additional file is not desired if possible).

My code so far looks like this:

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 )

Could you please help me?

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)

This should do it for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM