如何通过特定字符的位置读取txt文件

时间:2017-10-04 20:55:20

标签: python discord

我有一个代码,它读取文件并从该文件中随机选择一行,并通过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.")

1 个答案:

答案 0 :(得分:0)

正如您所解释的那样,您使用逗号(,)作为分隔符,因此您可以使用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

最后一个列表理解使用索引号旋转每一行,并且只保留偶数列。