Home > Software design >  Selecting a specific index, in a specific line in an external text file to alter
Selecting a specific index, in a specific line in an external text file to alter

Time:05-20

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?

CodePudding user response:

My solution is the least complicated among others, I think.

  1. You should first read the lines of the characters.txt to a list like this:
lines = open("char.txt", "r").readlines()
  1. Next you need to change the text you want (yes to no), which is in 2nd line:
lines[1] = lines[1].replace("yes", "no")
  1. Lastly, you need to write everything back to file:
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.

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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())
  • Related