如何在python中使用文本文件的特定行? [英] How do I use a specific line of a text file in python?

查看:63
本文介绍了如何在python中使用文本文件的特定行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文本文件是这样的:

My text file is this:

467 119 635 231 234 858
786 463 715 745 729 574 856 806 339 106 487
798 791 392 916 177 115 948 871 525

如您所见,有三行不同的数字值.我的任务是对它们进行排序,但仅对它们进行排序.因此,基本上,我需要将第一行从最小到最大排序,然后将第二行从最小到最大排序,并在第三行上相同.

As you can see, there are three separate lines with different number values. My mission is to sort them, but only the line they are on. So basically, i need to sort the first line from smallest to biggest, then the second line from smallest to biggest, and the same on the third line.

程序指定它需要使用此.txt文件中的值.因此,我想做的是一次查看每一行,并处理该行,用代码对其进行排序,然后将其放回原处.

The program specifies that it needs to use the values from this .txt file. So what I am wanting to do is look at each line one at a time and deal with that line, sort it with code, and put it back out.

我的问题是:如何让python一次只看一行?

My question is this: How do I get python to just look at one line at a time?

我知道这段代码读取第一行:

I know that this code reads the first line:

f = open("numbers.txt", "r")
f.readline()

但是我正在寻找一种可以只返回每一行的东西,这样我就可以使用该特定行的排序代码.

but I'm looking for something that returns just each line specifically, and that way I can work with my sorting code with that specific line.

说明:我并不是在寻求排序方面的帮助,我只是想弄清楚如何一次查看每一行.

Clarification: I'm not looking for help with the sorting, I'm just trying to figure out how to look at each line by itself at a time.

推荐答案

for line in f:
    nums = map(int, line.split())
    # looks at one line at a time, you can sort it now

如果要一次全部加载它们

If you want them all loaded at once

nums = [map(int, line.split()) for line in f]

现在,您可以像访问每个单独行的nums[0]nums[1]一样访问它.

Now you can access it like nums[0], nums[1] for each seperate line.

这篇关于如何在python中使用文本文件的特定行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆