-1
    f = open('2.txt', 'r')
    file_contents = f.read()
    print(file_contents)
    list = f.readline()
    print(sorted(f.readline()))

is returning "[]" as it's output. The contents of the file is:

Tom : 3

1 : 1

3 : 0

Tom : 1

You : 0

H : 0

Yo : 1

R : 0

Test : 0

T : 0

Yes : 0

3 : 0

T : 0

H : 0

Tesr : 0

G : 0

H : 0

V : 0

I want all the names listed in alphabetical order.

Anand S Kumar
  • 76,986
  • 16
  • 159
  • 156
  • 3
    When you do `f.read()` you have already read everything in the file and the cursor is at end, so after that doing `f.readline()` would simply return an empty string, and you are trying to sort that, which results in the empty list. – Anand S Kumar Oct 08 '15 at 06:22
  • Even without that, you are simply reading a single line and trying to sort its characters (you need to have a look into `f.readlines()` ). – Anand S Kumar Oct 08 '15 at 06:23

2 Answers2

0

You are reading the first line of your file, and it seems that you have not any string in your first line (maybe whitespace).

There is some points here first of all as a pythoinc way you can use with statement to open your file which close the file at the end of block, secondly you can use file.readlines() which returns all the lines in a list. But if you want to use sorted since file objects are iterable you can simply pass the file object to sorted :

with open('2.txt', 'r') as f :
    print(sorted(f))
kasravnd
  • 94,640
  • 16
  • 137
  • 166
0

Your code had already read in the whole file using f.read() which leaves the file pointer at the end. You can use f.seek() to move the file pointer back to the start as follows:

with open('2.txt', 'r') as f:       # Automatically close the file afterwards
    file_contents = f.read()        # Read whole file
    print(file_contents)            # Print whole file

    f.seek(0)                       # Move back to the start
    list = f.readline()             # Read first line again
    print(sorted(f.readline()))     # Sort the characters in the first line

You will then find that you only read the first line, and sorted() ends up sorting the characters within that line.

What you were probably looking to do is as follows:

with open('2.txt', 'r') as f:               # Automatically close the file afterwards
    file_contents = f.readlines()           # Read whole file as a list of lines
    print(''.join(sorted(file_contents)))   # Print the sorted lines

Which would display the following:

1 : 1
3 : 0
3 : 0
G : 0
H : 0
H : 0
H : 0
R : 0
T : 0
T : 0
Tesr : 0
Test : 0
Tom : 1
Tom : 3
V : 0Yes : 0
Yo : 1
You : 0
Martin Evans
  • 37,882
  • 15
  • 62
  • 83