簡體   English   中英

Python-在file.write()內部使用for循環

[英]Python - using for loop inside file.write()

我正在嘗試通過在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

用for循環包裝文件寫操作將解決您的問題。

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

for循環必須在外部:

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

我建議您將其with open…使用,這樣循環結束后,文件將自動關閉。

是的,那條線是各種各樣的錯誤。

您想在函數調用內部進行列表理解嗎?

將循環放到外面

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

但是您可以將列表加入一個字符串中

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

根據您要執行的操作,您似乎正在嘗試使用理解來合並並調用文件上的write。 您收到的語法錯誤是由於您對所要執行的操作的明顯誤用。 您實際上正在嘗試做的可能是這樣的:

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

但是, 這也是錯誤的 您將列表理解用於其副作用,這是列表理解的非常不好的用法。 您正在創建一個無用的列表,只是為了嘗試節省代碼行。

相反,如其他答案所述,進行迭代並調用write:

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

為了使您的代碼更健壯,額外的獎勵是為文件管理器使用上下文管理器,以便在使用文件后將其關閉。 當前,您應該在文件上顯式調用f.close() 因此,您可以執行以下操作:

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