如何在 python 中连续读取行
how to read lines in sequence continuously in python
我正在尝试使用 tweepy 制作推文机器人,它使用文本文件中的行连续推文
s = api.get_status(statusid)
m = random.choice(open('tweets.txt').readlines()).strip("\n")
api.update_status(status=m, in_reply_to_status_id = s.id)
print("[+] tweeted +1")
文件包含:
1st line
2nd line
3rd line
...
100th line
我不想只选择一个随机行,而是让它从第 1 行、第 2 行、...等等连续发推,直到所有行都发完推文。
而且我也想让它每次发推,数量都增加
[+] tweeted +1
[+] tweeted +2
...
[+] tweeted +100
这似乎是一个使用循环的非常简单的情况。Python 中的文件是可迭代的,因此您可以这样做:
with open('tweets.txt') as file: # a with statement ensures the file will get closed properly
for line in file:
... # do your stuff here for each line
由于您希望对已使用的行数进行 运行 计数,因此您可能需要添加对 enumerate
的调用,这会将您迭代的每个值与其配对一个数字(默认情况下从零开始,但您可以让它从 1 开始):
with open('tweets.txt') as file:
for num, line in enumerate(file, start=1):
...
我正在尝试使用 tweepy 制作推文机器人,它使用文本文件中的行连续推文
s = api.get_status(statusid)
m = random.choice(open('tweets.txt').readlines()).strip("\n")
api.update_status(status=m, in_reply_to_status_id = s.id)
print("[+] tweeted +1")
文件包含:
1st line
2nd line
3rd line
...
100th line
我不想只选择一个随机行,而是让它从第 1 行、第 2 行、...等等连续发推,直到所有行都发完推文。
而且我也想让它每次发推,数量都增加
[+] tweeted +1
[+] tweeted +2
...
[+] tweeted +100
这似乎是一个使用循环的非常简单的情况。Python 中的文件是可迭代的,因此您可以这样做:
with open('tweets.txt') as file: # a with statement ensures the file will get closed properly
for line in file:
... # do your stuff here for each line
由于您希望对已使用的行数进行 运行 计数,因此您可能需要添加对 enumerate
的调用,这会将您迭代的每个值与其配对一个数字(默认情况下从零开始,但您可以让它从 1 开始):
with open('tweets.txt') as file:
for num, line in enumerate(file, start=1):
...