Python - Set vars and loop over lines in file
Problem:
I have a text file - foo.bar inside of this file are lines of text: x-3411342 y-1324123 w-2314121 Each with a trailing \n to designate the end of the line. I am trying to read this file into python - which is simply in and of itself, however: Code:
What I want to do is open the contents of the file - read the line and set a variable - key, and for each line in the file, I want to do something with that key - but only once. So I want to read in a line, set to a variable, do something, print, and then do it for the next line. Any thoughts, pointers? |
I know exactly what you're talking about but cannot remember how to get around this. As you can imagine, it's not too hard, but I haven't used python in a few years...I'll keep thinking though! I'm wondering if you can make it a dictionary {} and fetch the keys instead... I vaguely remember this and now it's driving me nuts!
|
are these variables constant or do you change them regularly? If you set this up as dictionaries in the file, i.e., {'x':'3411342'} etc., you'll be able to pull out the values without having a '\n' tacked onto the end. basically, when you're entering your data, each line contains a '\n' that you don't see. When it prints to screen, or whereever, it also uses that plus it moves to the next line giving you that blank line you don't want.
Let me know if this or something else works for you. |
Your code could use a few more "pythonic" touches, it'll make it shorter and clearer. Observe:
Code:
f = file("foo.bar", "rb") # don't use open(), it's deprecated, and file() is |
pickle module
I was thinking more along these lines:
create your file with a dictionary instead of just plain text and use the pickle module: dict={'x':'x_val', 'y':'y_val', 'w':'w_val'} f=file(file_name, 'w') pickle.dump(dict, file_name) f.close() now to use your data: f=file(file_name, 'r') dict=pickle.load(f) f.close() for key in dict.keys(): data1, data2 = key, dict[key] This way you'll never have the '\n' associated with your values. |
Serializing is fine if you never want the user to be able to edit it. If you want a human-readable format, however ...
|
I agree. I was just passing on a different approach that would work fine in some applications.
|
All times are GMT -5. The time now is 04:22 AM. |