I am having trouble with the following logic.
I have an external txt file for example: characters.txt:
James, 24, blue, yes
Liam, 29, brown, yes
Michael, 40, brown, yes
If I wanted to change the yes in line 2 to 'no', how would I do this?
I am having trouble with the following logic.
I have an external txt file for example: characters.txt:
James, 24, blue, yes
Liam, 29, brown, yes
Michael, 40, brown, yes
If I wanted to change the yes in line 2 to 'no', how would I do this?
You could read line by line, and change line two. Or you could read it with pandas as a csv file, and change it that way.
f = open("characters.txt", "r")
print(f.readlines())
Then write it back.
Or use pandas (much nicer)
data=pandas.read_csv('character.txt', sep=',names=['name', 'age', 'color','answer']))
Then you access the answer column by writing:
answers = data['answer']
answers[1] = 'no'
data['answer'] = answers
This is just a psudocode, this could be done much neether if you want
From my understanding the best solution is to read the file into Python (array or df), modify it there and overwrite the original; it is not possible to modify external file directly.
Please check answers here: How to modify a text file?
PS. You might want to format the txt contents as code.
My solution is the least complicated among others, I think.
lines = open("char.txt", "r").readlines()
lines[1] = lines[1].replace("yes", "no")
open("char.txt", "w").writelines(lines)
Final Code:
lines = open("char.txt", "r").readlines()
lines[1] = lines[1].replace("yes", "no")
open("char.txt", "w").writelines(lines)
If other fellows have anything to add, please comment on this. Thanks.
Since your text file is CSV-like, you can use the built in csv
module.
from io import StringIO
import csv
# your input file, wrapped in StringIO to avoid writing it to file for me
s_in = StringIO("""\
James, 24, blue, yes
Liam, 29, brown, yes
Michael, 40, brown, yes
""")
# read file contents
reader = csv.reader(s_in)
lines = list(reader)
# prepare output file, might be same as input.
# again using StringIO for me to avoid writing to file, use with/open
s_out = StringIO()
# create csv writer, iterate through data, replace yes -> no on line 2, write
writer = csv.writer(s_out)
for i, line in enumerate(lines, 1):
if i == 2:
line[-1] = " no" # note the space here since delimiter is ", "
writer.writerow(line)
# print the contents of the file
print(s_out.getvalue())