|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Get inside! Sample the range of functionality easily built with JMSL Library for Time Series Data Analysis, Heat Maps, Portfolio Optimization, Monte Carlo Simulation, Stock Price Charting and more. Download Now! |
|
#1
|
|||
|
|||
|
Accessing text file
If i have a text file with these value:
Code:
## -- Text file --## nickname:realname something:anythin ##--- Text file --## how can I display the value of eg. nickname based on user input(eg: if the user type in nickname the the screen will display the real name) |
|
#2
|
|||
|
|||
|
Read the lines of the file, and store them somewhere. Then just lookup in the store when someone types something.
If you only want one-way lookups then a Dictionary is good to use. Code:
pairs = {}
for line in file('pairs.txt'):
try:
x, y = line.split(':')
pairs[x] = y
except:
#Ignore empty lines, etc.
pass
try:
val = raw_input('Type something: ')
print val, "links to", pairs[val]
except KeyError:
print val, "not found in pairs list"
|
|
#3
|
||||
|
||||
|
Often these files are edited by hand and around the values you want you get unwanted character codes (e.g. tabs and spaces) . You can tidy it up easily:
pairs[x.strip()] = y.strip() That might save a few hours bug-hunting .Grim
__________________
*** Experimental Python Markup CGI V2 *** |
|
#4
|
||||
|
||||
|
Just another example, based on sfb's with a few minor differences. Mainly to show the "if 'key' in dict" statment and stop unpacking errors.
1. only splitting on the first colon, this helps stop unpacking errors resulting from lines containing more than one colon. 2. uses if statments instead of try-except blocks. Just a personal preferance ![]() Code:
#!/usr/bin/env python
parts = {}
for line in file('file.txt'):
try:
x, y = line.split(':', 1)
parts[x] = y
except:
pass
value = raw_input('Enter a value')
if value in parts:
print value, 'links to', parts[value]
else:
print value, 'not found in parts'
Note: this does requite Python 2.3. Mark. Last edited by netytan : February 24th, 2004 at 03:14 PM. |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > Accessing text file |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|