如何从文本文件 python 中删除编号最大的行?
how do you delete the line with the biggest number from a text file python?
with open('winnernum.txt', 'r') as b:
data = b.readlines()
gone=(max(data))
print(gone)
with open("winnernum.txt","r") as h:
del gone
我已经在 python 中尝试过此代码和此代码的其他变体,但它仍然无法删除。我需要打印文本文件中前 5 个最大的数字。
我以前尝试过使用这个:
with open('winners.txt', 'r') as b:
data = b.readlines()
gone=(max(data))
print(gone)
import heapq
print(heapq.nlargest(5, winner))
但这并不总是选择前 5 个数字,而是倾向于 select 随机选择。请帮忙!
试试这个:
from contextlib import closing
with closing(open('winners.txt', 'r')) as file:
gone = max(map(lambda x: x.rstrip('\n'), file.readlines()))
print(gone)
这是一个简单的解决方案:
from heapq import nlargest
with open("winnernum.txt", "r") as f:
numbers = [float(line.rstrip()) for line in f.readlines()]
largest = nlargest(5, numbers)
print(largest)
with open('winnernum.txt', 'r') as b:
data = b.readlines()
gone=(max(data))
print(gone)
with open("winnernum.txt","r") as h:
del gone
我已经在 python 中尝试过此代码和此代码的其他变体,但它仍然无法删除。我需要打印文本文件中前 5 个最大的数字。
我以前尝试过使用这个:
with open('winners.txt', 'r') as b:
data = b.readlines()
gone=(max(data))
print(gone)
import heapq
print(heapq.nlargest(5, winner))
但这并不总是选择前 5 个数字,而是倾向于 select 随机选择。请帮忙!
试试这个:
from contextlib import closing
with closing(open('winners.txt', 'r')) as file:
gone = max(map(lambda x: x.rstrip('\n'), file.readlines()))
print(gone)
这是一个简单的解决方案:
from heapq import nlargest
with open("winnernum.txt", "r") as f:
numbers = [float(line.rstrip()) for line in f.readlines()]
largest = nlargest(5, numbers)
print(largest)