如何通过特定字符所在的位置读取 txt 文件
How To Read a txt File by Where A Specific Character Is
我有一个代码可以读取文件并从该文件中随机选择一行并将其作为不和谐机器人通过 DM 发送。但是,我希望它读取 txt 文件的某个部分,该部分以哪个字符开始和结束。
前任: ,
你好
,
这是我正在使用的代码,它读取随机行并通过 DM 发送它:
emailFile = open("C:/Users/jacob/Downloads/Spotify_premiums.txt", "r")
emails = []
for email in emailFile:
emails.append(email)
@bot.command(pass_context = True)
@commands.cooldown(1, 30, commands.BucketType.user)
@commands.has_any_role("| Premium |")
async def spotifypremium(ctx):
msg = emails
await bot.send_message(ctx.message.author, random.choice(msg))
await bot.send_message(ctx.message.channel, "Alt Has Been Seen To Your DMs")
await bot.purge_from(ctx.message.channel, limit=2)
await bot.send_message(ctx.message.author, "Please Wait 30 Seconds Before Using This Command Again. If you do not wait the full time then you won't be sent an alt.")
正如您所解释的,您使用逗号 (,
) 作为分隔符,因此您可以使用 str.split()
将文件分成逗号上的部分。
def load_file(fp):
with open(fp) as file:
content = file.read()
lines = content.split(",")
# Given ", hi ,", this will return ["", " hi ", ""]
# To clean the whitespace:
lines = [x.strip() for x in lines]
# To remove the empty start and end
lines = lines[1:-1]
# If your file is ", email 1 , email 2 , email 3 ,
# then you can return here, otherwise youll need to remove
# intermediate entries
lines = [l for i, l in enumerate(lines) if i % 2 == 0]
return lines
最后一个列表推导式用索引号分离每一行,只保留偶数。
我有一个代码可以读取文件并从该文件中随机选择一行并将其作为不和谐机器人通过 DM 发送。但是,我希望它读取 txt 文件的某个部分,该部分以哪个字符开始和结束。 前任: , 你好 ,
这是我正在使用的代码,它读取随机行并通过 DM 发送它:
emailFile = open("C:/Users/jacob/Downloads/Spotify_premiums.txt", "r")
emails = []
for email in emailFile:
emails.append(email)
@bot.command(pass_context = True)
@commands.cooldown(1, 30, commands.BucketType.user)
@commands.has_any_role("| Premium |")
async def spotifypremium(ctx):
msg = emails
await bot.send_message(ctx.message.author, random.choice(msg))
await bot.send_message(ctx.message.channel, "Alt Has Been Seen To Your DMs")
await bot.purge_from(ctx.message.channel, limit=2)
await bot.send_message(ctx.message.author, "Please Wait 30 Seconds Before Using This Command Again. If you do not wait the full time then you won't be sent an alt.")
正如您所解释的,您使用逗号 (,
) 作为分隔符,因此您可以使用 str.split()
将文件分成逗号上的部分。
def load_file(fp):
with open(fp) as file:
content = file.read()
lines = content.split(",")
# Given ", hi ,", this will return ["", " hi ", ""]
# To clean the whitespace:
lines = [x.strip() for x in lines]
# To remove the empty start and end
lines = lines[1:-1]
# If your file is ", email 1 , email 2 , email 3 ,
# then you can return here, otherwise youll need to remove
# intermediate entries
lines = [l for i, l in enumerate(lines) if i % 2 == 0]
return lines
最后一个列表推导式用索引号分离每一行,只保留偶数。