首页 > 解决方案 > 如何使文本文件连续读取Python中的下一行?

问题描述

我试图让它每隔几秒钟从文本文件中逐行打印每一行,并且每次打印到不和谐通道时我都尝试使用变量 += 1 ,但它会连续打印同一行。我使用 n 作为变量的输出图像,并让程序读取从 1 开始的第 n 行,每次读取一行时都会增加。我认为这会使它在文本文件中逐行读取,但似乎我错过了一些东西,想知道是否有人可以帮我找到它。谢谢你。

print(os.getenv("REPLIT_DB_URL"))
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
n=1

client = discord.Client()

@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')

message_channel=client.get_channel(845718766427439166)


with open('questions.txt') as f: 
  message_list = f.readline(n)
  qotd = message_list
  n+=1


#deletes the line


a_file = open("questions.txt", "r")

lines = a_file.readlines()
a_file.close()

del lines[0]

new_file = open("questions.txt", "w+")

for line in lines:
    new_file.write(line)

new_file.close()
  



@tasks.loop(seconds = 2)
async def called_once_a_day():
    message_channel = client.get_channel(845718766427439166)
    print(f"Got channel {message_channel}")
    await message_channel.send(qotd)

@called_once_a_day.before_loop
async def before():
    await client.wait_until_ready()
    print("Finished waiting")


called_once_a_day.start()


@client.event
async def on_message(message):
    if message.author == client.user:
        return
  




from discord.ext import commands

client = commands.Bot(command_prefix='$')

#monday

@client.command()
async def qotd_monday(ctx, sunday: str): 
  db["sunday"] = sunday
  await time.sleep(5)
  
  
  

@client.command()
async def qotd_list(ctx):
  await ctx.channel.send("1. " + (db["sunday"]) + "\n2. " + (db["saturday"]) + "\n3. " + (db["friday"]) + "\n4. " + (db["thursday"]) + "\n5. " + (db["wednesday"]) + "\n6. " + (db["tuesday"])+ "\n7. " + (db["monday"]))

client.run(TOKEN) TOKEN = os.environ['DISCORD_TOKEN']

标签: pythonfiletextdiscorddiscord.py

解决方案


尝试这个:

myfile = open("test.txt", "r")
for line in myfile:
    print(line)
    time.sleep(<time between prints>)
    myfile.close()

推荐阅读