简体   繁体   English

使用 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)

Im trying to read the second line (counterB) when I turned the bot on, so the counter doesn't restart当我打开机器人时,我试图读取第二行(counterB),所以计数器不会重新启动

Instead of getting the second line (counterB) value, I got the first line value(counterA) when i run the bot当我运行机器人时,我没有得到第二行(counterB)的值,而是得到了第一行的值(counterA)

So, Im trying to get a specific / certain line from counter.txt所以,我试图从 counter.txt 中获取特定/特定的行

readline() reads a file line by line. readline()逐行读取文件。

If you need a random line info from a file, you can use the readlines() method which returns the lines as a list and then you can use the index based access to directly get a particular line info.如果您需要文件中的随机行信息,您可以使用readlines()方法将行作为列表返回,然后您可以使用基于索引的访问来直接获取特定的行信息。

For example, to get second line value, use the following:例如,要获取second行值,请使用以下命令:

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

f.readlines() returns a list of lines, eg my txt file looks like this: f.readlines()返回行列表,例如我的 txt 文件如下所示:

Hello world!
This is something
I'm writing

The return result of f.readlines would be: f.readlines的返回结果将是:

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

Let's say I want the second line:假设我想要第二行:

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

If you want only one line,then instead of reading all lines,read untill you get N th line,如果你只想要一行,那么不要阅读所有行,而是阅读直到你得到第 N 行,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM