This is an instructional tutorial that will guide you on how to make use of Python to grep a word in a file. Understanding how to grep in Python is an essential skill to have, especially if you work with large amounts of text data.
The Grepping technique allows you to filter out specific words in a text file. This can be very useful for data analysis, data mining, and general programming tasks.
Step 1: Set Up the Environment
To grep a word in a file using Python, you will need to have Python installed on your PC. If you don’t have Python installed, you can download it from the official Python website.
Step 2: Creation of a Text File
For this tutorial, we have to create a text file that will act as our test data. Create a text file named ‘sample.txt’ with the following content:
Hello world Python is great Python is interpreted Hello Python!
Step 3: Writing The Python Code
Now that we have our test data, we will create a function, named grep_word, that will take in a word and a filename as parameters. It will open the file and scan through each line, looking for occurrences of the word.
Here’s a snapshot of the code:
1 2 3 4 5 |
def grep_word(word, filename): with open(filename,'r') as file: for line_no, line in enumerate(file, 1): if word in line: print(f'line {line_no}: {line.rstrip()}') |
The grep_word function opens the file in ‘read’ mode and starts looping through each line. If a line contains the word, it outputs the line number along with the line.
Step 4: Use of the Function
With the function in place, let’s use it to grep the word ‘Python’ from ‘sample.txt’
1 |
grep_word('Python', 'sample.txt') |
Full Code
Below is the full code put together:
1 2 3 4 5 6 7 |
def grep_word(word, filename): with open(filename, 'r') as file: for line_no, line in enumerate(file, 1): if word in line: print(f'line {line_no}: {line.rstrip()}') grep_word('Python', 'sample.txt') |
When the code is run, it greps the word “Python” from the file sample.txt and prints the lines containing the word “Python”, along with their line numbers.
Conclusion
That’s it! You’ve successfully learned how to grep a word from a file using Python. Understanding how to grep in Python is an essential skill that will help you in a wide range of tasks including file manipulation, data analysis, or web scraping.
Keep in mind that the grep
technique used in this tutorial is a simple Python implementation and might not fully replace the more powerful Unix grep
for large-scale applications. Nonetheless, it’s a step towards understanding file manipulation and string searching techniques in Python.
If you want to further improve your Python skills and learn more about file handling and string operations, consider visiting the official Python documentation.