Skip to main content

How to sort lines in a text file alphabetically in Python

How to sort lines in a text file alphabetically in Python.

Here is a detailed step-by-step tutorial on how to sort lines in a text file alphabetically using Python:

Step 1: Read the text file

To begin, we need to read the contents of the text file into a Python list. We can achieve this by using the open() function to open the file, and then the readlines() method to read all the lines into a list.

with open('input.txt', 'r') as file:
lines = file.readlines()

In the above code, replace 'input.txt' with the path to your text file.

Step 2: Sort the lines

Once we have the lines stored in a list, we can use the sorted() function to sort them alphabetically. By default, sorted() will sort the lines in ascending order.

sorted_lines = sorted(lines)

After executing this code, sorted_lines will contain the sorted lines from the text file.

Step 3: Write the sorted lines to a new text file

Now that we have the sorted lines, we can write them to a new text file. We will use the open() function again, this time with the 'w' parameter to open the file in write mode. Then, we can iterate over the sorted lines and write each line to the file using the write() method.

with open('output.txt', 'w') as file:
for line in sorted_lines:
file.write(line)

In the above code, replace 'output.txt' with the desired path and name for the sorted output file.

Step 4: Verify the sorted output

After executing the code, you can check the newly created output file to verify that the lines have been sorted alphabetically.

Complete code example:

with open('input.txt', 'r') as file:
lines = file.readlines()

sorted_lines = sorted(lines)

with open('output.txt', 'w') as file:
for line in sorted_lines:
file.write(line)

Remember to replace 'input.txt' with the path to your input file and 'output.txt' with the desired path and name for the output file.

That's it! You have successfully sorted the lines in a text file alphabetically using Python.