Practical 6: Program to read a line from a file split it into words using spaces and display the result.
Problem Statement
Write a Python program to read a line from a file, split it into words using spaces, and display the result.
Solution Code
# Program to split a line into words using space as the separator
# Open the file in read mode
file = open("sample.txt", "r")
# Read the first line from the file
line = file.readline()
# Split the line into words using space as the delimiter
words = line.split()
# Display the words
print("Words in the line:", words)
# Close the file
file.close()
Output
If the sample.txt file contains:
Python programming is fun and powerful. File handling is an important concept.
After running the program, the output will be:
Words in the line: ['Python', 'programming', 'is', 'fun', 'and', 'powerful.']
Process finished with exit code 0
Explanation
Below is the explanation of F.E. PPS Unit 4 Practical 6 solution where we have written python program to read a line from a file split it into words using spaces and display the result.
- Opening the File in Read Mode
- open(“sample.txt”, “r”) opens the file in read mode (r), ensuring the file can be read.
- Reading a Line from the File
- file.readline() reads only the first line from the file.
- Splitting the Line into Words
- split() method breaks the line into words wherever there is a space.
- Displaying the Words
- The list of words is printed to the console.
- Closing the File
- file.close() ensures that system resources are freed after file operations.
Key Concepts Learned
- Using readline() to Read a Single Line
- Instead of reading the entire file, this method reads only one line at a time.
- Splitting a String Using split()
- split() method is used to break a string into a list of words based on spaces by default.
- File Handling Best Practices
- Always close the file after performing operations.