【问题标题】:Remove file data - Python删除文件数据 - Python
【发布时间】:2020-09-30 03:33:55
【问题描述】:
#name,scores
a,6
b,8
c,2
k,23
d,18
r,13
w,4
h,9
threshold = input("Enter minimum score: ")

我有一个 TXT 文件,我希望删除低于某个分数阈值的数据。

例如,如果用户输入 10,则文件应输出以下内容:

k,23
d,18
r,13

【问题讨论】:

  • 这个“文件”是什么? txt、csv?另外,你试过什么?
  • @Nelver 是txt,我是初学者所以不知道怎么办

标签: python file append


【解决方案1】:

我假设名称和分数在文本文件中,而您从 python 文件中获取用户输入。

代码:

import sys

threshold = int(input("Enter in a number: "))
with open("text.txt", "r") as f:
    for i in f:
        num = i.split(",", 1)[1]
        if (int(num) > threshold ):
            sys.stdout.write(i) # didn't use print() because it puts an extra newline


文本文件:

#name,scores
a,6
b,8
c,2
k,23
d,18
r,13
w,4
h,9

输出:

k,23
d,18
r,13

【讨论】:

  • 如果这对你有帮助,别忘了批准答案:)
  • name,vote 不在文件中。你能调整一下代码吗
  • @Daniel 即使您没有姓名,代码仍然有效,请在文本文件中投票,但为了您的方便,我还是删除了代码:)
  • 另外,请记住接受此答案,以便将来的用户可以轻松找到它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
  • 2021-11-10
  • 2017-02-14
  • 2020-04-24
  • 2022-01-06
相关资源
最近更新 更多