如何从用户指定的txt列表中删除行?

2024-04-25 17:55:58 发布

您现在位置:Python中文网/ 问答频道 /正文

这里是Python 101。我为一个咖啡店老板创建了一个程序来跟踪库存。我应该“通过允许所有者从文件中删除数据来修改文件。请所有者输入要删除的描述。如果描述存在,请删除咖啡名称和数量。如果找不到描述,则显示消息:文件中找不到该项。“到目前为止,我收到的建议是将文件内容读取到行列表中,过滤掉我不需要的行,然后将列表写回文件。你知道吗

这是我目前掌握的情况

with open('coffeeInventory.txt', 'w') as f:
    f.write('Blonde Roast=15\n')
    f.write('Medium Roast=21\n')
    f.write('Flavored Roast=10\n')
    f.write('Dark Roast=12\n')
    f.write('Costa Rica Tarrazu=18\n')
    f.close()
sum=0

with open('coffeeInventory.txt', 'r') as f:
    for line in f.readlines():
        sum += int(line.split("=")[1])
        print(line)
f.close()

print('Total Pounds of Coffee= ', sum)

with open('coffeeInventory.txt') as f:
  lineList = f.readlines()
lineList= [line.rstrip('\n') for line in open('coffeeInventory.txt')]
print(lineList)

Tags: 文件txt列表forcloseaswithline
2条回答

也许这能让你开始

import io

f = io.StringIO()

f.write('Blonde Roast=15\n')
f.write('Medium Roast=21\n')
f.write('Flavored Roast=10\n')
f.write('Dark Roast=12\n')
f.write('Costa Rica Tarrazu=18\n')

f.seek(0)

lineList = f.readlines()

print(lineList)

deleteThis = 'Dark Roast'

newList = [line for line in lineList if deleteThis not in line]

print(newList)

我会从其他答案中选择另一种方式,实际上建议使用JSON文件。你知道吗

首先,你必须建立一个字典。字典中的每个元素都有一个键和一个值。你知道吗

coffee_inventory = {
    "Blonde Roast": 15
}

您可以通过在方括号内指定名称来访问库存。你知道吗

coffee_inventory["Blonde Roast"]

Output: 15

要向字典中添加键和值,只需在方括号中指定键,然后指定等号和值。你知道吗

coffee_inventory["Medium Roast"] = 21

因此,现在字典应该是这样的:

coffee_inventory = {
    "Blonde Roast": 15,
    "Medium Roast": 21
}

您必须使用JSON来保存和检索文件。你知道吗

import json

coffee_inventory = {
    "Blonde Roast": 15,
    "Medium Roast": 21
}

# Saving the JSON to a file.
# "indent=4" is for better styling.
with open("inventory.json", "w") as file:
    json.dump(coffee_inventory, file, indent=4)

# Retrieving the JSON.
with open("inventory.json", "r") as file:
    coffee_inventory = json.load(file)

print(coffee_inventory)

Output: {'Blonde Roast': 15, 'Medium Roast': 21}

最后,要删除一个值,只需使用del。例如,删除“金发烤”你做以下。你知道吗

del coffee_inventory["Blonde Roast"]

这就是你需要知道的关于JSON的所有信息,我相信你可以将本指南中的所有内容连接到你的程序中,使之比以前更好。你知道吗

相关问题 更多 >