简体   繁体   English

Python-在file.write()内部使用for循环

[英]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. 我正在尝试通过在file.write中运行for循环来打印所有端口,但以下语法错误给了我。

 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. 用for循环包装文件写操作将解决您的问题。

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: for循环必须在外部:

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. 我建议您将其with open…使用,这样循环结束后,文件将自动关闭。

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. 根据您要执行的操作,您似乎正在尝试使用理解来合并并调用文件上的write。 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: 相反,如其他答案所述,进行迭代并调用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. 当前,您应该在文件上显式调用f.close() So, you can do: 因此,您可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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