如何从已创建的csv文件中操作数据

2024-04-20 04:16:48 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我正在尝试使用Telegram的API,制作一个程序,从csv文件中获取数据,并向Telegram上的用户发送个性化消息。这个程序运行良好,但我想从csv文件中操作数据,以忽略特定用户的用户名或只是删除他们在csv文件中的行,这样他们就不会收到消息。你知道吗

我尝试过将pandas集成起来,但我不知道如何使用它,我只是把代码弄乱了。你知道吗

input_file = sys.argv[1]
users = []
with open(input_file, encoding='UTF-8') as f:
    rows = csv.reader(f,delimiter=",",lineterminator="\n")
    next(rows, None)
    for row in rows:
        user = {}
        user['username'] = row[0]
        user['id'] = int(row[1])
        user['access_hash'] = int(row[2])
        user['name'] = row[3]
        users.append(user)

mode = int(input("Enter 1 to send by user ID or 2 to send by username: "))



OR 


for user in users:
    if mode == 2:
        if user['username'] == "":
            continue
        receiver = client.get_input_entity(user['username'])
    elif mode == 1:
        receiver = InputPeerUser(user['id'],user['access_hash'])
    else:
        print("Invalid Mode. Exiting.")
        client.disconnect()
        sys.exit()
    message = random.choice(messages)
    try:
        print("Sending Message to:", user['name'])
        client.send_message(receiver, message.format(user['name']))
        print("Waiting {} seconds".format(SLEEP_TIME))
        time.sleep(SLEEP_TIME)

Tags: 文件csvtonameclientsendinputmode