【问题标题】:Deleting part of an I/O file python删除部分 I/O 文件 python
【发布时间】:2016-12-09 02:47:10
【问题描述】:

我正在尝试构建一个程序,该程序将在 I/O 文件中记录学生的姓名和年级。问题是当用户在删除函数中从文件中删除名称时。谢谢你看:)

(x是用户给的名字)

    def remove(x):
    with open ("grades.txt", "rt") as f:
            text = f.read()

    if x in text:

            new = del text[x]
            with open ("grades.txt", "wt") as f:
                    text = f.write(new)

    else:
            print("name not in the file")

【问题讨论】:

  • 你的问题到底是什么?
  • 您如何存储以及要删除什么?具体一点。
  • @MohammadYusufGhazi 不要编辑帖子中的空白,尤其是关于 Python 的帖子。空格在 Python 中在语法上很重要,如果问题出在 WS 本身,您最终会屏蔽它。
  • @MohammadYusufGhazi 为什么要在编辑中从代码中删除错误? 不要
  • @S.Grym 请edit您的问题并输入minimal reproducible example。还请附上任何错误或追溯的全文

标签: python io


【解决方案1】:

由于 x 和 text 是字符串,因此您首先要在 text 中找到 x 的起始索引。

if x in text:
    start_index = text.index(x)
    end_index = start_index + len(x)
    # so text[start_index:end_index] is x

    # Now to remove it:
    new = text[:start_index] + text[end_index:]

编辑: 根据您存储名称的方式,您可能还需要删除逗号或换行符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 2012-05-01
    相关资源
    最近更新 更多