如何遍历文本文件并用python打印下一个数字?

2024-04-25 22:27:07 发布

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

如何浏览文本文件并打印下一个升序数字和其他信息(已经可以这样做了)?你知道吗

对于我的代码,我需要分配一个数字给用户输入的东西,到目前为止,我能做的一切,但得到的数字打印到文本文件。我希望我的文件按以下方式格式化:

1 abcd

2efgh

我需要的代码,通过文本文件,看看什么是最高的数字,然后打印与信息下一个数字。就像我之前说的,我对信息部分没有任何问题,只是添加数字的部分。你知道吗

我曾经考虑过做一个if语句,但是这意味着要经历很多数字,迟早需要用更多的数字来更新。除此之外,这将是非常耗时和内存消耗。你知道吗

我也考虑过使用for语句,但是我还没有找到一种工作的方法。你知道吗

任何帮助都将不胜感激。谢谢


Tags: 文件内存代码用户信息if方式数字
2条回答

试图建立自己的数据库。使用csv可以将读取和解析工作卸载到现有模块。使用一个数据库,这样您就可以处理自动分配的数字,避免重复的数字,条目不按顺序,添加新的列,等等

# Read the file and get the last line:
with open('data.txt') as f:
    last_line = f.readlines()[-1]


# Take the number from it and add a new number 
# (assumes the file is sorted so the biggest number is always on the last line)
# because if you're only using this script to add things, it always will be
last_num, _ = last_line.split(' ')
new_num = int(last_num) + 1


# Read from the user and make a new line:
new_text = input('Type stuff here: ')       
new_line = "{0} {1}".format(new_num, new_text)


# Write the new line ('a' is append mode)
with open('data.txt', 'a') as f:
    f.writeline(new_line)

考虑到你的档案文件.txt“并且行的格式与您指定的一样,这样就可以完成:

s = list(map(lambda x: int(x.split()[0]), open('file.txt').read().split('\n')))
next = max(s) + 1

要使用下一个数字添加用户输入,请使用以下命令(与前几行一起使用):

data = input('Enter you data: ')
open('file.txt', 'a').write('\n' + str(next) + ' ' + data)

解释:

open('file.txt').read().split('\n')-打开文件,然后按行拆分

map(lambda x: int(x.split()[0]), ...)-获取每行中第一个元素的integer强制转换

list(...)-将map对象强制转换为list索引对象

max(s) + 1-获取检索到的最大值,递增1

open('file.txt', 'a')-在appending模式下打开文件(不要刷新文件,从末尾开始并添加附件)

write('\n' + str(next) + ' ' + data)-用指定格式的下一个数字添加数据(\n表示下行)

相关问题 更多 >