如何在撰寫原始程式的 MAIN 檔案中創建一個撰寫 print("hello world") 的程式?在 Python 中
如果我想運行一個在我撰寫原始程式的主檔案的代碼中寫入 print("hello world") 的程式,我該怎么做?在 Python 中
我想是這樣的:
import main
with open("main.py " , "a ") as file_object:
file_object.seek(0)
data = file_object.read(100)
if len(data)>0:
file_object.write("\n")
file_object.write('print("hello world)')
但控制臺顯示:
ValueError:對已關閉檔案的 I/O 操作。
uj5u.com熱心網友回復:
據我了解,您正在嘗試確定檔案是否有內容以及是否包含新行,然后附加列印陳述句。
你不需要使用 seek 你可以只檢查檔案的大小:
import os
if os.path.getsize(filename):
# file isn't empty
else:
# file is empty
您還應該關閉列印陳述句中的引號
uj5u.com熱心網友回復:
您可以使用__file__which 為您提供檔案的路徑,然后將您的文本附加到它。
path = __file__
f = open(path, "a")
f.write('\nprint("hello world")')
f.close
uj5u.com熱心網友回復:
你錯了,因為縮進正確,就像這樣。您可以修改如下:
import main
with open("main.py" , "a ") as file_object:
file_object.seek(0)
data = file_object.read(100)
if len(data)>0:
file_object.write("\n")
file_object.write('print("hello world")')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/463665.html
標籤:Python
下一篇:將整數值轉換為周(年-周格式)
