Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

How do I use a specific line of a text file in 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.

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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]

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...