简体   繁体   中英

How to add increased number on every output

First, here is my code that I have.

s = api.get_info(1230)
my_file=open('textlist.txt','r')
file_lines=my_file.readlines()
my_file.close()
###############
for line in file_lines:
    try:
        print("[+] Trying to post "+line)
        if line != '\n':
           api.update(line, post_id = s.id)
        else:
            pass
    except api.msgError as e:
        print(e.msg)
        #set interval per replies
    print("[+] Success +1...")
    sleep(10)
###############

And the textlist.txt file is

line_1
line_2
line_3
...
line_10

Output

[+] Trying to post line_1
[+] Success +1...
[+] Trying to post line_2
[+] Success +1...
...

And now how can I make the output for [+] Success +1 ** to be increased every time it successfully posts the line**, like this

[+] Trying to post line_1
[+] Success +1...
[+] Trying to post line_2
[+] Success +2...
...
[+] Trying to post line_10
[+] Success +10...

Like this:

for n_success , line in enumerate(file_lines, 1):
    try:
        print("[+] Trying to post "+line)
        if line != '\n':
           api.update(line, post_id = s.id)
        else:
            pass
    except api.msgError as e:
        print(e.msg)
        #set interval per replies
    print(f"[+] Success +{n_success}...")
    sleep(10)

The other answers fail to address when updating fails. You should create a variable for the number of successes that only increments if the update succeeded.

Also consider using a with -statement to open your file. It will ensure the file is closed if there is an exception while it's open and is considered good practice.

s = api.get_info(1230)
with open('textlist.txt','r') as my_file
    file_lines=my_file.readlines()
###############
n_successes = 0
for line in file_lines:
    try:
        print("[+] Trying to post "+line)
        if line != '\n':
           api.update(line, post_id = s.id)
           n_successes += 1 # Increment it here
           print(f"[+] Success {n_successes}...")
        else:
            pass
    except api.msgError as e:
        print(e.msg)
        #set interval per replies
    sleep(10)
print(f"Total number of successes: {n_successes}")
###############

You have a delimiter in each line use that to your advantage.

Instead of:

print("[+] Success +1...")

Use:

print(f"[+] Success +{line.split('-')[1]}...")

Or:

print("[+] Success +{}...".format(line.split('-')[1]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM