python - 如何使文本文件连续读取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']
解决方案
尝试这个:
myfile = open("test.txt", "r")
for line in myfile:
print(line)
time.sleep(<time between prints>)
myfile.close()
推荐阅读
- reactjs - 为什么我需要做 export const useAppDispatch = () => useDispatch
() 将 Typescript 与 React 一起使用时 - azure - Azure Devops Pipeline 返回:“无法将 Web 包部署到应用服务。内部服务器错误(代码:500)'
- amazon-dynamodb - 在响应映射模板中访问状态码
- c++ - 基于优化级别的特征切换类型和执行
- python-3.x - Python 多处理 pool.async: 'TypeError("cannot pickle '_io.BufferedReader' object")'
- c# - c# imazen.webp 旋转图片框后将 .webp 保存为 .webp 图像
- python - 从python中的URL读取xls文件
- java - “'StoredProcController' 中构造函数的参数 0 需要一个名为 'oracleEntityManager' 的 bean,但无法找到”Spring Boot 应用程序
- python - 图表类:TypeError:__init__() 接受 1 个位置参数,但给出了 3 个
- r - 使用ggplot2在一定半径内绘制点之间的路径