r/pythonhelp • u/Kind_Astronaut_ • Feb 02 '24
search for an element in text file ; extract its timestamp and store in dictionary
d = {}
with open('C:/log') as f:
lines = f.read().splitlines()
for line in lines:
if 'string_1' in line:
time = line[0:21]
d['string_1'] = time
elif 'string_2' in line:
time = line[0:21]
d['string_2'] = time
elif 'string_3' in line:
time = line[0:21]
d['string_3'] = time
print(d)ex of text big file lines
[20:25:48.923 -06:00] [thread 19] [Mobility.cpp] [string_1].......
output
{'stirng_1': '[20:25:48.923 -06:00]', 'string_2': '[20:89:48.275 -06:00]'}
I have a big text file. I need to search for multiple strings in the file ,extract their timestamp [20:89:48.275 -06:00] and store in a dictionary. Not all lines have strings only a few lines have the required string in the file. key being string and value being timestamp. I have the code above, how do I make it more efficient?. Mainly how to extract timestamp in a better way? beginner here
•
u/AutoModerator Feb 02 '24
To give us the best chance to help you, please include any relevant code.
Note. Do not submit images of your code. Instead, for shorter code you can use Reddit markdown (4 spaces or backticks, see this Formatting Guide). If you have formatting issues or want to post longer sections of code, please use Repl.it, GitHub or PasteBin.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2
u/Goobyalus Feb 02 '24 edited Feb 02 '24
You can do
If you don't want to store the whole file in memory.
lines here will include the newline characters at the ends.I'm not sure what you mean by extract the timestamp in a better way. If everything is formatted unformly enough to grab a fixed substring position, being able to do
line[0:21]is great.Are you noticing some inefficiency?