Reading files in Python is a crucial task when working with data. In this tutorial, we’ll learn how to read a file word by word in Python. This can come in handy when you want to manipulate specific words in a file.
Example
Let’s create a file called filename.txt with the following content:
one two three four five
Steps to Read A File Word By Word In Python
Step 1: Open the file using the open() function
Before we can read the contents of a file, we need to open it first. We can do this using the open() function. This function takes two arguments – the name of the file to be opened and the mode we want to open it.
1 |
file = open('filename.txt', 'r') |
The ‘r’ in the second argument specifies that we want to open the file in read mode.
Step 2: Use the read() function to read the contents of the file
Once we have opened the file, we can read its contents using the read() function. This function reads the entire file as a string.
1 |
content = file.read() |
Step 3: Split the string into words
Now that we have the contents of the file as a string, we can split it into words using Python’s split() method.
1 |
words = content.split() |
This will give us a list of all the words in the file.
Step 4: Loop through the list of words and do what you need to do with each word
Finally, we can loop through the list of words and perform any operations we need to do with each word.
1 2 |
for word in words: print(word) |
Result
one two three four five
Conclusion
In this tutorial, we learned how to read a file word by word in Python. By following these simple steps, you should be able to manipulate specific words in a file with ease.
1 2 3 4 5 6 |
file = open('filename.txt', 'r') content = file.read() words = content.split() for word in words: print(word) |