简体   繁体   中英

Trying to read a txt file with numbers into a list and then sort using Python

I have a one line txt file, file1.txt, that has a series of 10 numbers as such;

10,45,69,85,21,32,11,71,20,30

I want to take these numbers from the txt file and then add them to a list and then sort the numbers in ascending order.

I have tried

myfile1 = open('file1.txt', 'r').readlines()

but this seems to give me a list of length 1, which obviously can't be sorted.

In [101]: myfile1
Out[101]: ['10,45,69,85,21,32,11,71,20,30']

I'm guessing there is something wrong with how I am reading the text file however I can't seem to find a suitable way.

A little obfuscated to do as a 1-liner, but basically:

with open('file1.txt', 'r') as f:
    data = sorted(map(int, f.readline().split(',')))

What this does:

  1. Read 1 line: f.readline()
  2. Split that line on ',' characters: .split(',')
  3. Map the list of string to int values: map(int, list)
  4. Sort the list of int : sorted(list)

.readlines() does what it says: it reads the file in line by line. In your example, there is only one line, so the length is 1.

With that one line, you need to split on commas:

with open(file1.txt,'r') as myfile:
    for line in myfile:
        print sorted(map(int, line.split(',')))

Or, if you have multiple lines with lots of numbers:

data = []
with open(file1.txt,'r') as myfile:
    for line in myfile:
        data.extend(map(int, line.split(',')))
print sorted(data)

Here I use with with keyword to open the file, which can be iterated over line by line. Then, use the the split method of strings on each line, which returns a list of strings. Then, I use map to convert these strings into integers by applying the int type casting function to each item in the list. This list can then be sorted. Make sure to take a look at the string methods page on the Python documentation.

A test without the input file:

numbers = "10,45,69,85,21,7,32,11,71,20,30"
data = []
data.extend(map(int, numbers.split(',')))
print sorted(data)

prints

[7, 10, 11, 20, 21, 30, 32, 45, 69, 71, 85]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM