'Python - Need to delete everything before and after a variable in a string [closed]
I am needing to read data out of a text file and locate certain fields contained within. I've gotten the txt file into a string but now I'm needing to locate certain fields. The file looks like:
City: New York
First Name: John
Last Name: Jones
Address: 123 Main St.
If I were wanting to pull the first name "John" out, what is the best way to do that in python? I know I can do a .find for "First Name: " but then how to I use that index to delete everything before and after "John" so I'm just left with a varialbe "John"
readData = open("data.txt", more='r')
rawData = readData.read()
readData.close()
x = rawData.index("First Name:")
Solution 1:[1]
Since you are using such a clean and regular format you can do this pretty easily by reading each line and splitting on : using str.split.
with open("some_file.txt") as file:
for line in file:
key, value, = line.split(": ", maxsplit=1)
or you can use a dictionary comprehension for a cleaner data structure representation:
with open("some_file.txt") as file:
{key, value for key, value in [line.split(": ", maxsplit=1) for line in file]}
Note that you will probably also want to wrap these in a try-catch block to handle badly made or corrupted files where there is a missing key or missing value.
Solution 2:[2]
For storing this kind of data, i would really suggest using JSON; as it is very easy to use and versatile, here's an example:
data.json file:
{
"city": "New York",
"first_name": "John",
"last_name": "Jones",
"address": "123 Main St."
}
Python file:
import json #Python supports JSON from the get-go!
json_data = json.load(open("data.json"))
city = json_data['city']
first_name = json_data['first_name']
last_name = json_data['last_name']
address = json_data['last_name']
Solution 3:[3]
You could do it like this:
def main():
with open("./data.txt", "r") as f:
searched_key = "First Name"
value = ""
for line in f:
if searched_key in line:
value = line[len(searched_key) + 2:]
print(value)
You should implement it as a function to be more handy. Just make searched_key a parameter and return value.
Also using jsons or dictionaries are easier and faster than txt.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Ramón de León |
| Solution 3 | Yann Bernard |
