简体   繁体   English

Python:如何将列表中的文本+元素保存到txt文件

[英]Python: how to save text + element from the list to the txt file

I'm learning Python and I'm trying to combine saving text + specific element from the list to a txt file.我正在学习 Python,我正在尝试将保存文本 + 列表中的特定元素组合到一个 txt 文件中。

I managed to get the text out and it looks like this:我设法把文字弄出来,它看起来像这样:

Project name: Main worker: Project name: Main worker:项目名称: 主要工作人员: 项目名称: 主要工作人员:

and this is fine but I would like to add workers and projects that are in the lists to look like this:这很好,但我想添加列表中的工作人员和项目,如下所示:

Project name: Microsoft Main tester: Michael Scott Project name: Amazon Main tester: Dwight Schrute项目名称:Microsoft 主要测试人员:Michael Scott 项目名称:Amazon 主要测试人员:Dwight Schrute

And I'm not sure how to add that, this is what I got so far:而且我不确定如何添加它,这是我到目前为止所得到的:

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()

If I understood you correctly, just writing the names and projects like you did with the headers (eg "Project name:") would be sufficient.如果我理解正确的话,只需像您对标题所做的那样编写名称和项目(例如“项目名称:”)就足够了。 For example:例如:

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()

For lists, you can access the first element with a list[0], the second one with list[1] and so on.对于列表,您可以使用 list[0] 访问第一个元素,使用 list[1] 访问第二个元素,依此类推。 This is however a fairly manual approach and you could use a loop here to iterate over the list entries if you have more entries later on.然而,这是一种相当手动的方法,如果以后有更多条目,您可以在此处使用循环来遍历列表条目。

I not sure about your input and output data but I hope I understand it correct.我不确定您的输入和 output 数据,但我希望我理解正确。 And because you are a Python learner I took the liberty to introduce some other Python techniques to make the solution more Pythonic and less error prone.因为你是一个 Python 学习者,我冒昧地介绍了一些其他 Python 技术,使解决方案更像Pythonic并且更不容易出错。

The full example完整的例子

#!/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())

The resulting projects.txt file look like this.生成的projects.txt文件如下所示。 Is this what you wanted?这是你想要的吗?

Project name:
Jenny Boe
Main worker:
John Doe
Project name:
Project Beta
Main worker:
Project Alpha
 

Step-by-step explained逐步解释

I removed the two classes from your example code because I couldn't see an advantage of them.我从您的示例代码中删除了这两个类,因为我看不到它们的优势。 I also removed the input() part and hard coded some sample data.我还删除了input()部分并对一些示例数据进行了硬编码。 Hope this is OK that way?希望这样可以吗?

# example data (assuming both lists with same length)
all_workers = ['John Doe', 'Jenny Boe']
all_projects = ['Project Alpha', 'Project Beta']

To interact with files and the filesystem it is recommended to use Pythons pathlib package. The with block in the code make sure that the file is closed automatically when the block ends.要与文件和文件系统交互,建议使用 Pythons pathlib package。代码中的with块确保文件在块结束时自动关闭。

import pathlib
    
projects_file_path = pathlib.Path('projects.txt')

# open the file
with projects_file_path.open('w') as file_handle:
    # write...

I think the for -loop is self explaining.我认为for循环是自我解释的。 It's advantage is it prevents you from write repetitiv code.它的优点是它可以防止您编写重复代码。

I constructed the string written into the file with the f -string like this.我用这样的f字符串构建了写入文件的字符串。

file_handle.write(f'Project name:\n{project}\n')

But you could also use the old way with format() .但是您也可以使用format()的旧方法。

file_handle.write('Project name:\n{}\n'.format(project))

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

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