我正在學習 Python,我正在嘗試將串列中的文本 特定元素保存到 txt 檔案中。
我設法把文本拿出來,它看起來像這樣:
專案名稱: 主要工人: 專案名稱: 主要工人:
這很好,但我想添加串列中的工人和專案,如下所示:
專案名稱:Microsoft 主要測驗人員:Michael Scott 專案名稱:亞馬遜主要測驗人員:Dwight Schrute
而且我不知道如何添加,這是我到目前為止得到的:
class Worker:
def __init__(self, name, lastname):
self.name = name
self.lastname = lastname
def name_lastname(self):
print(self.name, self.name)
class Project:
def __init__(self, name, worker):
self.name = name
self.worker = worker
workers = []
projects = []
name1 = input("Enter the name: ")
lastname1 = input("Enter the last name: ")
workers.append(name1 ' ' lastname1)
name2 = input("Enter the name: ")
lastname2 = input("Enter the last name: ")
workers.append(name2 ' ' lastname2)
projectname1 = input("Enter the name of the project: ")
projectname2 = input("Enter the name of the project: ")
projects.append(projectname1)
projects.append(projectname2)
print(workers)
print(projects)
file = open("projects.txt","w")
file.write("Project name: \n")
file.write("Main worker: \n")
file.write("Project name: \n")
file.write("Main worker: \n")
file.close()
uj5u.com熱心網友回復:
如果我理解正確,只需像使用標題一樣撰寫名稱和專案(例如“專案名稱:”)就足夠了。例如:
file.write("Project name: \n")
file.write(projects[0] "\n")
file.write("Main worker: \n")
file.write(workers[0] "\n")
file.write("Project name: \n")
file.write(projects[1] "\n")
file.write("Main worker: \n")
file.write(workers[1] "\n")
file.close()
對于串列,您可以使用 list[0] 訪問第一個元素,使用 list[1] 訪問第二個元素,依此類推。然而,這是一種相當手動的方法,如果以后有更多條目,您可以在此處使用回圈來迭代串列條目。
uj5u.com熱心網友回復:
我不確定您的輸入和輸出資料,但我希望我理解正確。因為您是 Python 學習者,所以我冒昧地介紹了一些其他 Python 技術,以使解決方案更符合Python 風格且不易出錯。
完整的例子
#!/usr/bin/env python3
import pathlib
# example data (assuming both lists with same length)
all_workers = ['John Doe', 'Jenny Boe']
all_projects = ['Project Alpha', 'Project Beta']
# file path
projects_file_path = pathlib.Path('projects.txt')
# open the file
with projects_file_path.open('w') as file_handle:
# iterate over your lists side by side
for worker, project in all_workers, all_projects:
file_handle.write(f'Project name:\n{project}\n')
file_handle.write(f'Main worker:\n{worker}\n')
# let's look what is in the file
with projects_file_path.open('r') as file_handle:
print(file_handle.read())
生成的projects.txt檔案如下所示。這是你想要的嗎?
Project name:
Jenny Boe
Main worker:
John Doe
Project name:
Project Beta
Main worker:
Project Alpha
一步一步解釋
我從您的示例代碼中洗掉了這兩個類,因為我看不到它們的優勢。我還洗掉了該input()部分并硬編碼了一些示例資料。希望這樣可以嗎?
# example data (assuming both lists with same length)
all_workers = ['John Doe', 'Jenny Boe']
all_projects = ['Project Alpha', 'Project Beta']
要與檔案和檔案系統互動,建議使用 Pythonspathlib包。代碼中的with塊確保檔案在塊結束時自動關閉。
import pathlib
projects_file_path = pathlib.Path('projects.txt')
# open the file
with projects_file_path.open('w') as file_handle:
# write...
我認為for-loop 是自我解釋的。它的優點是它可以防止您撰寫重復代碼。
f我用這樣的-string構造了寫入檔案的字串。
file_handle.write(f'Project name:\n{project}\n')
但您也可以使用舊方式與format().
file_handle.write('Project name:\n{}\n'.format(project))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/478290.html
下一篇:保存到檔案時串列分隔字母
