使用 f.readline() - Discord.py 读取特定行

Reading a specific line with f.readline() - Discord.py

async def token():
  global counterA
  global counterB
  
  counterA = 0
  counterB = 0
  
  
  while True:
    await asyncio.sleep(5)
    counterA += 1
    counterB += 2
    
    with open('counter.txt', 'w') as f:
        f.write (str(counterA))
        f.write ("\n")
        f.write (str(counterB))
        f.write ("\n")

@client.event
async def on_ready():
    global counterA
    global counterB

    with open('counter.txt', 'r') as f:
      counterA = int(f.readline())
    with open('counter.txt', 'r') as f:
      counterB = int(f.readline())

    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

client.loop.create_task(token())
client.run(TOKEN)

我在打开机器人时尝试读取第二行 (counterB),因此计数器没有重新启动

当我 运行 机器人

时,我没有获得第二行 (counterB) 值,而是获得了第一行值 (counterA)

所以,我正在尝试从 counter.txt

中获取特定/特定行

readline() 逐行读取文件。

如果您需要文件中的随机行信息,您可以使用 readlines() 方法,将 returns 行作为列表,然后您可以使用基于索引的访问直接获取特定线路信息。

例如,要获取 second 行值,请使用以下内容:

with open('counter.txt', 'r') as f:
      lines = f.readlines()
      secondLine = lines[1]

如果你只想要一行,那么不要读取所有行,而是读取到第 N 行,

s=''
for i in range(n) :
  s=f.readline()

f.readlines() returns 行列表,例如我的 txt 文件如下所示:

Hello world!
This is something
I'm writing

f.readlines 的 return 结果将是:

result = ["Hello World!\n", "This is something\n", "I'm writing\n"]

假设我想要第二行:

>>> line = 2
>>> result[line - 1] # Remember, indexes start at 0
"This is something\n"