LAB-6
Program 6: Develop a program to sort the contents of a text file and write the
sorted contents into a separate text file. [Hint: Use string methods strip(), len(),
list methods sort(), append(), and file methods open(), readlines(), and write()].
def sort_file_contents(input_file, output_file):
with open(input_file, 'r') as file:
contents = [Link]()
contents = [[Link]() for line in contents]
[Link](key=len)
with open(output_file, 'w') as file:
for line in contents:
[Link](line + '\n')
# Call the function
sort_file_contents('[Link]', '[Link]')
Algorithm:
1. Start
2. Open the input file:
• Open the input file ([Link]) in read mode.
3. Read file contents:
• Read all the lines from the input file.
• Store the lines in a list called contents.
4. Remove leading/trailing whitespaces:
• Iterate through each line in contents and remove any leading or trailing
whitespace using the strip() method.
5. Sort the lines by length:
• Sort the list contents in ascending order of the length of each line using the
sort() method with key=len.
6. Open the output file:
• Open the output file ([Link]) in write mode.
7. Write the sorted contents:
• Iterate through each line in the sorted list contents and write it to the output file.
• Ensure that each line is written with a newline character (\n).
8. Close the files:
• Close both the input and output files (implicitly handled when using with).
9. End
Output:
Output file is the sorted contents of input file.