0

I have this txt file with usernames and some data related to them

vac3,Javier Jerez,34,Femenino,0,0
jotaaa23,Ssef Sef,34,Masculino,0,0
asd,Asdas Asd,23,Masculino,0,0
attd,Asd Asd,23,Femenino,0,0
ssdfd,Dgs Sef ,24,Femenino,0,0
asdfsdfd,Javier Jerez,12,Masculino,0,0

I want to modify the last 2 numbers

For example vac3 won a game with 90 points in 7 shots, i want the new list to be

vac3,Javier Jerez,34,Femenino,90,7
jotaaa23,Ssef Sef,34,Masculino,0,0
asd,Asdas Asd,23,Masculino,0,0
attd,Asd Asd,23,Femenino,0,0
ssdfd,Dgs Sef ,24,Femenino,0,0
asdfsdfd,Javier Jerez,12,Masculino,0,0

I've tried everything and nothing seems to work, i know i have to read the txt to a list, then rewrite data in that list, and then overwrite the whole txt. May i get some help pls.

Javier Jerez
  • 360
  • 4
  • 16
  • 1
    How can the programmer know that vac3 should end with 90,7? Where does that data come from? – kojiro Mar 12 '20 at 21:03
  • Which part are you struggling with, specifically? – AMC Mar 12 '20 at 21:19
  • 1
    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) – AMC Mar 12 '20 at 21:19
  • https://stackoverflow.com/questions/26903304/reading-data-from-a-csv-file-in-python – AMC Mar 12 '20 at 21:20

3 Answers3

0

If you don't want to use csv.reader:

who, score, shots = "vac3", 90, 7

with open("yourfile.txt", "r") as f:
    with open('newfile.txt', 'w') as out:
        for line in f:
            fields = line.rstrip().split(',')
            if fields[0] == who:
                fields[4] = score
                fields[5] = shots
            out.write(','.join(fields) + '\n')
Błotosmętek
  • 12,717
  • 19
  • 29
0

Try this:

with open('players.txt', 'r') as f:
    players = []
    data = f.readlines()
    winner = 'vac3'
    scores = ['90', '7']
    for line in data:
        player = line.split(',')
        if player[0] == winner:
            player[4] = scores[0]
            player[5] = scores[1]
        players.append(player)

with open('players.txt', 'w') as f:
    f.writelines('')
    for player in players:
        plr = ','.join(player) + "\n"
        f.write(plr)
Javier Jerez
  • 360
  • 4
  • 16
0

You can use regex to identify the pattern and replace

import re

inpt = "vac3,90,7".split(',')
fmt = f"^({inpt[0]},.*,)\d+,\d+$"
new_txt = ""
with open('t.txt', 'r') as read_f, open('new.txt', 'w') as write_f:
    for line in read_f:
        new_txt += re.sub(fmt, fr"\g<1>{inpt[1]},{inpt[2]}", line)
    write_f.write(new_txt)
Teshan Shanuka J
  • 1,448
  • 2
  • 17
  • 31