简体   繁体   中英

Python - using for loop inside file.write()

I am trying to print all the ports by running for loop inside file.write but its giving me below syntax error.

 ports = ["123", "234"] 
 # mentioned only 2 ports but I have more than 200 ports
 f = open("test.html", "w")
 f.write( for i in range(0, len(port)):
 File "<stdin>", line 1
 f.write( for i in range(0, len(port)):
           ^
 SyntaxError: invalid syntax

Wrapping the file write operation with the for loop will solve your problem.

ports = ["123", "234"]
f = open("test.html", "w")
for i in range(0, len(ports)):
    f.write(ports[i] + '\n')

The for loop needs to be on the outside:

with open("test.html", "w") as f:
    for i in range(0, len(port)):
        f.write(i + '\n')

I recommend you use with open… , this way the file is automatically closed as soon as the loop is finished.

Yeah, that line is all sorts of wrong.

You want a list comprehension inside of the function call why?

Put the loop outside

for port in ports_list:
    f.write(port + '\n') 

But you could join the list into one string

f.write('\n'.join(ports_list)) 

Based on what you are trying to do, you seem to be attempting to combine using a comprehension and calling the write on the file. The syntax error you are getting is because of the clear misuse of what you are trying to do. What you are actually trying to do, is probably something like this:

[f.write(x) for x in port]

However, this is wrong as well. You are using a list comprehension for its side effects, which is a very bad use of a list comprehension. You are creating a useless list just for the sake of trying to save lines of code.

Instead, as mentioned in the other answers, iterate, and call write:

for port in ports:
    f.write("{}\n".format(ports))

Extra bonus, to make your code more robust, is to make use of a context manager for your file manager, so that the file gets closed after you use it. Currently, you should be explicitly be calling an f.close() on your file. So, you can do:

with open("test.html", "w") as f:
    for port in ports:
        f.write("{}\n".format(port))

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