0

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
2
  • Are you trying to write the strings inside ports into your html file? Commented Mar 12, 2017 at 16:40
  • yes Xenyal .. i.e what I need to achieve finally. Commented Mar 12, 2017 at 16:45

4 Answers 4

1

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')
Sign up to request clarification or add additional context in comments.

2 Comments

Am getting all port numbers in a single line but I need them in separate lines cat test.html 123234
@Premchand That's simple to resolve. Check my edit for getting them on separate lines.
1

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.

Comments

0

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)) 

Comments

0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.