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