将文本文件中的整数值加 1,然后将这个新值写在旧值之上?

Adding 1 to an integer value in a text file and then writing this new value on top of the old value?

我正在尝试获取文本文件中位置 [1] 处存在的已参加的高尔夫球场数,并将其加 1。我设法做到了这一点,但现在想更新整数值。目前程序只是在下一行写入新值而不是更新。

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]))

目前文本文件如下所示:

Tom Jones,1
2

我希望 2 位于 1 所在的位置:(

我会使用这样的方法:

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)

阅读整个文件,根据需要修改每一行,并在进行过程中构建输出。然后,一旦您通读了整个文件,请返回文件的开头并用新内容覆盖旧内容。

您需要将该文件读取到缓冲区,编辑它并再次将其写入文件。

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)

类似的东西。

希望对您有所帮助。

将所有数据读入行列表,修改行,写回数据。我选择创建一个新文件:

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

输出:

# April.txt
Tom Jones,3
Tim,50

# April_new.txt
Tom Jones,4
Tim,50

如果您需要处理多名游泳者,您可能还想看看 Change specific value in CSV file via Python

这可能是另一个解决方案:

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)

不带缓冲区的选项使用 csv 和 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)