0

I am trying to get the number of golfing sessions that have been attended which exists at position position [1] in the text file and add 1 to it. I have manged to do this but now want to update the integer value. Currently the program just writes the new value on the next line instead of updating.

with open("%s.txt" % month, 'r+') as f:
  for line in f:
    lineList = line.split(",")
    if golferssName == lineList[0]:
      numSessions = int(lineList[1])
      numSessions = int(numSessions) + 1
      ineList[1] = numSessions
      f.write(str(lineList[1]))

at the moment the text file looks like this:

Tom Jones,1
2

I want the 2 to be where the 1 is :(

David Lamb
  • 21
  • 2
  • 2
    You need to read file in buffer, edit what you need and rewrite file with modified data, otherwise, even if you'll fix code, it won't work properly in case if amount of digits in new number is different. – Olvin Roght Apr 01 '20 at 13:38
  • what is that for `if swimmersName == lineList[0]` – Shubham Shaswat Apr 01 '20 at 13:42
  • @ShubhamShaswat, isn't it obvious? – Olvin Roght Apr 01 '20 at 13:44
  • @OlvinRoght ok I think understand now,I thought all the names in the list are swimmers, – Shubham Shaswat Apr 01 '20 at 13:48
  • I am wish it was obvious :-) been staring at the screen a while now. Could you explain in simple terms. I don't think I am a million miles away. I have manged to get the existing number and I have added 1. Just need to overwrite the old value now?? – David Lamb Apr 01 '20 at 13:50

5 Answers5

1

Read in all data into lists of lines, modify line, write data back out. I choose to create a new file:

month = "April"
swimmersName = "Tom Jones"

with open(f"{month}.txt","w") as f:
    f.write(f"{swimmersName},3\nTim,50")

data = []
with open(f"{month}.txt") as f:
        for line in f:
            if line and ("," in line):
                data.append( line.strip().split(",") )
                if data[-1][0] == swimmersName:
                    data[-1][1] = str(int(data[-1][1])+1)

with open(f"{month}_new.txt","w") as w:
        for (user,visits) in data:
            w.write(f"{user},{visits}\n")

print(open(f"{month}.txt").read())
print(open(f"{month}_new.txt").read())

Output:

# April.txt
Tom Jones,3
Tim,50

# April_new.txt
Tom Jones,4
Tim,50

See How to overwrite a file correctly?

If you need to handle multiple swimmers you might want to take a look at Change specific value in CSV file via Python as well.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

I would use an approach like this:

out = ""

with open("foo.txt","r+") as f:
    for line in f:
        tokens = line.split(",")
        out += tokens[0] + "," + str(int(tokens[1])+1) + "\r\n"

    f.seek(0)
    f.write(out)

Read the entire file, modifying each line as you need to, and build an output as you go along. Then, once you've read through the entire file, seek back to the beginning of the file and overwrite the old contents with the new ones.

Kexus
  • 659
  • 2
  • 6
  • 13
0

You will need to read that file to a buffer edit it and write it to the file again.

out = []
with open("path", 'r+') as f:
  for line in f:
    lines = line.split(",")

    numSessions = int(lines[1])
    numSessions = int(numSessions) + 1
    lines[1] = numSessions
    out.append(lines)
print(out)
lines  = [','.join(map(str,i)) for i in out]
print(lines)
with open("path", 'w') as f:
  f.writelines(lines)

Something like that.

Hope it helps.

0

this could be another solution:

with open("%s.txt" % month, 'r') as f:
    newfilelines = []
    filelines = f.readlines()
    for fileline in filelines:
        lineList = fileline.split(",")
        if swimmersName == lineList[0]:
            lineList[1] = int(lineList[1]) + 1
            newfilelines.append(lineList[0] + ',' + str(lineList[1]) + '\n')
with open("%s.txt" % month, 'w') as f:
    for newfileline in newfilelines:
        f.write(newfileline)
gekigek99
  • 303
  • 3
  • 17
  • f.truncate() AttributeError: 'str' object has no attribute 'truncate' – David Lamb Apr 01 '20 at 14:31
  • 2.py", line 149, in takeRegister f.write(filelines) TypeError: write() argument must be str, not list – David Lamb Apr 01 '20 at 14:47
  • @DavidLamb I modified the code so that now it works without problem. I have used 2 open commands so it's not 100% great but it gets the job done now. – gekigek99 Apr 01 '20 at 16:10
0

Option without buffer using csv and os:

import csv, os

swimmersName = 'Tom Jones'
in_file = 'test.txt'

with open(in_file, newline='') as csv_reader:
    with open('temp.txt', mode='w', newline='') as csv_writer:
        reader = csv.reader(csv_reader, delimiter=',')
        writer = csv.writer(csv_writer, delimiter=',')
        for row in reader:
            if row[0] == swimmersName:
                row[1] = int(row[1]) + 1
            writer.writerow(row)

os.rename('temp.txt', in_file)
Saxasmu
  • 384
  • 4
  • 8