【问题标题】:Reading a specific line with f.readline() - Discord.py使用 f.readline() 读取特定行 - Discord.py
【发布时间】:2021-04-27 15:58:11
【问题描述】:
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(),第一次只有关闭,而不是两次。

标签: python discord bots discord.py readline


【解决方案1】:

readline() 逐行读取文件。

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

例如,要获取second 行值,请使用以下命令:

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

【讨论】:

  • 请注意,这意味着您需要将整个文件放入内存中,这可能会占用大量内存,具体取决于您的文件大小。
  • @BryanFBT 问题不在于它是否有效,而在于您应该意识到您正在使用的功能中内置的任何低效率。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

    Hello world!
    This is something
    I'm writing
    

    f.readlines 的返回结果是:

    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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-15
      • 2012-12-22
      相关资源
      最近更新 更多