我正在嘗試撰寫一個代碼,該代碼將獲取用戶輸入的資訊并將其永久添加到不同檔案的變數中:
主要.py:
text = "hello world"
f = open("Testfile.py", "a ")
f.write(text)
測驗檔案.py:
w = ["bob", "joe", "emily"]Hello World
我怎樣才能讓“Hello World”出現在 w 中,例如
w = ["bob", "joe", "emily", "Hello World"]
編輯:
如果 w 是一個庫,例如
w = {"bob": 0, "joe": 0, "emily" : 0}
我想添加"Hello World" : 0到它
uj5u.com熱心網友回復:
真的有必要將陣列的內容存盤到 python 檔案中嗎?例如,您可以將其存盤到 yaml 檔案中,而您可以使用 yaml 庫來向/從該檔案寫入和讀取內容。
import yaml
import os
def load_yaml(filename):
with open(filename, 'r') as fp:
y = yaml.safe_load(fp)
return y
def save_yaml(content, filename):
if os.path.exists(filename):
os.remove(filename)
with open(filename, 'w') as fp:
yaml.safe_dump(content, fp, default_flow_style=False)
w = ["bob", "joe", "emily"]
save_yaml(w, "data.yaml")
w.append("hello world")
save_yaml(w, "data.yaml")
content = load_yaml("data.yaml")
print(content)
uj5u.com熱心網友回復:
我強烈建議不要以編程方式修改 python 檔案。通過將串列存盤在文本檔案中并讓任何程式讀取文本檔案并構建串列,您可能能夠完成相同的任務。還有其他檔案格式可以用于更復雜的任務,但對于簡單地將字串放入串列中,此代碼就足夠了。某種完整的資料庫最適合實際應用程式。
測驗.txt:
bob
joe
emily
主要.py:
def read_file():
f = open('test.txt', 'r')
lines = f.readlines()
lines = [line.strip() for line in lines] #removes the '\n' character at the end of each line
print(lines)
f.close()
def append_file(item):
f = open('test.txt', 'a')
f.write(item)
f.write('\n')
f.close()
read_file()
append_file("Hello World")
append_file("test")
read_file()
另外作為獎勵,您可以使用with更簡潔地管理檔案物件。
def read_file():
with open('test.txt', 'r') as f:
lines = f.readlines()
lines = [line.strip() for line in lines] #removes the '\n' character at the end of each line
print(lines)
def append_file(item):
with open('test.txt', 'a') as f:
f.write(item)
f.write('\n')
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/311499.html
上一篇:如何確保串列為空白
