-3

What I want to do: I have a few lists in a text file now and want to change just 1 element of 1 of the lists using python. What I have done so far:

Current txt file:

food,bought
oranges,yes
strawberry,no
apples,no

I want it to appear like this after using the code to replace one of the "no" to "yes":

food,bought
oranges,yes
strawberry,no
apples,yes

Is there any way to specifically change one index of the list?

ellle
  • 5
  • 3
  • 2
    Can you please clarify what you want to do? Files don't have indices, yet lists are trivial to change. Do you want to change a *list read from the file* or do you want to change the *file itself*? – MisterMiyagi Feb 21 '20 at 19:57
  • 1
    Welcome to StackOverflow. [On topic](https://stackoverflow.com/help/on-topic), [how to ask](https://stackoverflow.com/help/how-to-ask), and ... [the perfect question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) apply here. – Prune Feb 21 '20 at 20:12
  • Does this answer your question? [Change specific value in CSV file via Python](https://stackoverflow.com/questions/11033590/change-specific-value-in-csv-file-via-python) – Gino Mempin Feb 22 '20 at 11:21

3 Answers3

0

If the file is small enough to fit in memory you can just read it, replace it and rewrite it.

idx = 3
with open(file_name, 'r') as f:
    file = f.readlines()

line = file[idx].split(',')
line[1] = 'yes'
file[idx] = ','.join(line)

with open(file_name, 'w') as f:
    for line in file:
        f.write(line)
Luis Da Silva
  • 313
  • 2
  • 8
0

This worked for me:

def change_file(index):
with open("test.txt", 'r+') as file:
    lines = file.readlines()
    for i, line in enumerate(lines):
        if i == index:
            lines[i] = line.replace('no', 'yes')
    file.seek(0)
    file.writelines(lines)

change_file(3)
John
  • 69
  • 3
0

You can change the value of any index by loading the file using pandas Dataframe and using .loc depending on your requirements.

For Example:

import pandas as pd
data = pd.read_csv("filename.txt", sep=",")
print (data)
>>> 
         food bought
0     oranges    yes
1  strawberry     no
2      apples     no

Now to change some index, there are multiple ways to do that.

  1. Specific Index: index can be int or list.
index=2
data.loc[index, "bought"] = "yes"
>>> 
         food bought
0     oranges    yes
1  strawberry     no
2      apples    yes
  1. Filter with value: If you know which values you are looking to change, filter them using the conditions such as this and add the replacement value.
data.loc[data["food"] == "apples", "bought"] = "yes"
>>>
         food bought
0     oranges    yes
1  strawberry     no
2      apples    yes
shaivikochar
  • 400
  • 2
  • 7