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
Solution 1:
.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]
Solution 2:
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:
- Read 1 line:
f.readline()
- Split that line on
','
characters:.split(',')
- Map the
list
ofstring
toint
values:map(int, list)
- Sort the
list
ofint
:sorted(list)
Post a Comment for "Trying To Read A Txt File With Numbers Into A List And Then Sort Using Python"