Reputation: 91
I'm trying to create a python script to look up for a specific string in a txt file For example I have the text file dbname.txt includes the following :
Level1="50,90,40,60"
Level2="20,10,30,80"
I will need the script to search for the user input in the file and print the output that equals that value Like :
Please enter the quantity : 50
The level is : Level1
I am stuck in the search portion from the file ? any advise ?
Thanks in advance
Upvotes: 1
Views: 2282
Reputation: 395075
In these sorts of limited cases, I would recommend regular expressions.
import re
import os
You need a file to get the info out of, make a directory for it, if it's not there, and then write the file:
os.mkdir = '/tmp'
filepath = '/tmp/foo.txt'
with open(filepath, 'w') as file:
file.write('Level1="50,90,40,60"\n'
'Level2="20,10,30,80"')
Then read the info and parse it:
with open(filepath) as file:
txt = file.read()
We'll use a regular expression with two capturing groups, the first for the Level, the second for the numbers:
mapping = re.findall(r'(Level\d+)="(.*)"', txt)
This will give us a list of tuple pairs. Semantically I'd consider them keys and values. Then get your user input and search your data:
user_input = raw_input('Please enter the quantity: ')
I typed 50, and then:
for key, value in mapping:
if user_input in value:
print('The level is {0}'.format(key))
which prints:
The level is Level1
Upvotes: 1
Reputation: 28036
Use the mmap module, the most efficient way to do this hands down. mmap doesn't read the entire file into memory (it pages it on demand) and supports both find() and rfind()
with open("hello.txt", "r+b") as f:
# memory-map the file, size 0 means whole file
mm = mmap.mmap(f.fileno(), 0)
position = mm.find('blah')
Upvotes: 0