0% found this document useful (0 votes)
418 views3 pages

Python Lab Program 6

The document outlines a program that sorts the contents of a text file by line length and writes the sorted lines to a separate output file. It provides a function, 'sort_file_contents', which reads from an input file, removes whitespace, sorts the lines, and writes them to an output file. The algorithm details the steps involved in this process, including file handling and sorting methods.

Uploaded by

angelotommy006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
418 views3 pages

Python Lab Program 6

The document outlines a program that sorts the contents of a text file by line length and writes the sorted lines to a separate output file. It provides a function, 'sort_file_contents', which reads from an input file, removes whitespace, sorts the lines, and writes them to an output file. The algorithm details the steps involved in this process, including file handling and sorting methods.

Uploaded by

angelotommy006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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.

You might also like