2

I have found the following Python code from Stackoverflow which opens a file called sort.txt, and then sorts the the numbers contained in the file.

The code works perfect. I was wondering how I could then save the sorted data to another text file. Every time I try, the saved file is shown empty. Any help would be appreciated. I would like the saved file to be called sorted.txt

with open('sort.txt', 'r') as f:
    lines = f.readlines()
numbers = [int(e.strip()) for e in lines]
numbers.sort()

3 Answers 3

1

You can use this with f.write() :

with open('sort.txt', 'r') as f:
    lines = f.readlines()

numbers = [int(e.strip()) for e in lines]
numbers.sort()

with open('sorted.txt', 'w') as f: # open sorted.txt for writing 'w'
    # join numbers with newline '\n' then write them on 'sorted.txt'
    f.write('\n'.join(str(n) for n in numbers))

Input (sort.txt):

1
-5
46
11
133
-54
8
0
13
10

Output (sorted.txt):

-54
-5
0
1
8
10
11
13
46
133
Sign up to request clarification or add additional context in comments.

Comments

1

With <file object>.writelines() method:

with open('sort.txt', 'r') as f, open('output.txt', 'w') as out:
    lines = f.readlines()
    numbers = sorted(int(n) for n in lines)
    out.writelines(map(lambda n: str(n)+'\n', numbers))

Comments

0

Get sorted data from the current file and save to a variable. Open the new file in write mode ('w')and write the data from saved variable to the file.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.