To extract data from a text file in Python, you’ll typically read the file line by line and process the content according to your requirements. Here’s a simple example to get you started:
Let’s assume you have a text file named data.txt with the following content:
Name: CodeTryout
Age: 25
Occupation: Software Engineer
Name: Python Developer
Age: 30
Occupation: Data Scientist
Here’s a Python script to read this file and extract the information:
def extract_data(file_path):
# Open the file in read mode
with open(file_path, 'r') as file:
# Initialize variables to store extracted data
current_person = {}
all_people = []
# Read the file line by line
for line in file:
# Check if the line is empty (end of a person's information)
if line.strip() == '':
if current_person:
# Append the current person's data to the list
all_people.append(current_person)
# Reset current_person for the next iteration
current_person = {}
else:
# Split each line into key and value
key, value = line.strip().split(': ')
# Store key-value pair in the current_person dictionary
current_person[key] = value
# Append the last person's data (if any) to the list
if current_person:
all_people.append(current_person)
return all_people
# Example usage
file_path = 'data.txt'
extracted_data = extract_data(file_path)
# Print the extracted data
for person in extracted_data:
print("Name:", person.get("Name", ""))
print("Age:", person.get("Age", ""))
print("Occupation:", person.get("Occupation", ""))
print()
In this example, the script reads the text file line by line, separates the key and value using split(‘: ‘), and stores the information in a dictionary (current_person). When an empty line is encountered, it considers that the information for one person is complete, and it appends the dictionary to a list (all_people). The script then prints the extracted data for each person.
You can customize this script based on the structure and content of your text file.