首页 > 解决方案 > 通过玩一些文本文件来了解读写文件。在 Python 3 中

问题描述

假设我们有一个包含酒店当前访客的文本文件。我们称之为guests.txt。运行以下代码来创建文件。该文件将在其自己的行中自动填充每个初始客人的名字。

guests = open("guests.txt", "w")
initial_guests = ["Bob", "Andrea", "Manuel", "Polly", "Khalid"]
​
for i in initial_guests:
    guests.write(i + "\n")
    
guests.close()
No output is generated for the above code cell. To check the contents of the newly created guests.txt file, run the following code.

with open("guests.txt") as guests:
    for line in guests:
        print(line)
Bob

Andrea

Manuel

Polly

Khalid

输出显示我们的 guest.txt 文件在其自己的行中正确填充了每个初始来宾的名字。凉爽的!

现在假设我们想在客人入住和退房时更新我们的文件。在以下单元格中填写缺少的代码,以便在客人登记入住时将客人添加到 guest.txt 文件中。

new_guests = ["Sam", "Danielle", "Jacob"]
​
with open("guests.txt", "w") as guests:
    for i in new_guests:
        guests.write(i + "\n")
​
guests.close()
To check whether your code correctly added the new guests to the guests.txt file, run the following cell.

with open("guests.txt") as guests:
    for line in guests:
        print(line)
Sam

Danielle

Jacob

guest.txt 文件中的当前名称应该是:Bob、Andrea、Manuel、Polly、Khalid、Sam、Danielle 和 Jacob。

新来宾是否正确附加了 guest.txt 文件?如果没有,请返回并编辑您的代码,确保适当地填补空白,以便将新客人正确添加到 guest.txt 文件中。成功添加新客人后,您已正确填写缺少的代码。伟大的!

现在让我们删除已经签出的客人。有几种方法可以做到这一点,但是,我们将为此练习选择的方法概述如下:

以“读取”模式打开文件。遍历文件中的每一行并将每个客人的姓名放入 Python 列表中。以“写入”模式再次打开文件。将 Python 列表中每个客人的姓名一一添加到文件中。

准备好?在以下单元格中填写缺少的代码以删除已签出的客人。

checked_out=["Andrea", "Manuel", "Khalid"]
temp_list=[]

with open("guests.txt",___) as guests:
    for g in guests:
        temp_list.append(g.strip())
checked_out=["Andrea", "Manuel", "Khalid"]
temp_list=[]
​
with open("guests.txt",___) as guests:
    for g in guests:
        temp_list.append(g.strip())
​
with open("guests.txt",___) as guests:
    for name in temp_list:
        if name not in checked_out:
            guests.___(name + "\n")

标签: python

解决方案


试试这个答案问题1

guests = open("guests.txt", "w")
initial_guests = ["Bob", "Andrea", "Manuel", "Polly", "Khalid"]

for i in initial_guests:
    guests.write(i + "\n")

guests.close()

问题2

new_guests = ["Sam", "Danielle", "Jacob"]

with open("guests.txt",'a') as guests:
    for i in new_guests:
        guests.write(i + "\n")

guests.close()

问题 3

checked_out=["Andrea", "Manuel", "Khalid"]
temp_list=[]

with open("guests.txt",'r') as guests:
    for g in guests:
        temp_list.append(g.strip())

with open("guests.txt",'w') as guests:
    for name in temp_list:
        if name not in checked_out:
            guests.write(name + "\n")

推荐阅读