簡體   English   中英

如何通過特定字符所在的位置讀取txt文件

[英]How To Read a txt File by Where A Specific Character Is

我有一個讀取文件的代碼,並從該文件中隨機選擇一行,並將其作為不和諧的bot通過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

最后的列表理解從帶有索引號的每一行中分離出來,僅保留偶數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM