Reputation: 407
Im still new to file I/O in python, and so I'm having some trouble with figuring out how to look for a specific variable in a file.
This is the file i'm opening(txt type):
grelha = [['O', 'H', 'L', 'E', 'M', 'R', 'R', 'V', 'U'],
['B', 'B', 'R', 'A', 'N', 'C', 'O', 'Z', 'A'],
['S', 'R', 'A', 'M', 'S', 'U', 'P', 'A', 'O'],
['A', 'A', 'B', 'A', 'P', 'O', 'T', 'Z', 'Z'],
['L', 'N', 'Z', 'R', 'O', 'E', 'R', 'N', 'U'],
['I', 'U', 'I', 'E', 'P', 'D', 'O', 'I', 'I'],
['L', 'O', 'L', 'L', 'O', 'R', 'A', 'C', 'A'],
['I', 'T', 'M', 'O', 'T', 'E', 'R', 'P', 'P'],
['L', 'I', 'E', 'A', 'Z', 'V', 'Y', 'U', 'U']]
palavras = ['branco','preto','azul','verde','rosa','amarelo','vermelho','cinza','lilas']
And this is the code I've got:
def file():
game_file = open(str(input("What is the name of the file?")), "r+")
for i in game_file:
if i == 'grelha':#"I've tried without it being a string as well"
print (i)
As far as I could find out there isn't any method to help me do this, and I also don't quite well understand how the iteration works in this case.
If anyone could help me out with this problem and explain the iteration that would be great!
Upvotes: 0
Views: 55
Reputation: 856
By default, python read file by line, so your if i == 'grelha'
will get nothing.
If you want to find the line start with palavras, you can use startwith()
method:
In [3]: for line in file:
...: if line.startswith('palavras'):
...: print line
...:
palavras = ['branco','preto','azul','verde','rosa','amarelo','vermelho','cinza','lilas']
For file, iteration works line by line; For str, iteration works char by char;
Generally, python treat file as string, so you can't write python code in file, the line palavras = ['branco','preto','azul','verde','rosa','amarelo','vermelho','cinza','lilas']
is string, not code. You still need to parse them.
Upvotes: 0
Reputation: 16275
What you're doing seems to naively assume that just because the file content is valid python, opening it with python will parse it as python. This is absolutely not the case. You need to choose a format for storing your data so that it can be interpreted properly when you need to read it back in.
For example, you might find JSON to be a perfect way to store this kind of structured data:
{"grelha": [["O", "H", "L", "E", "M", "R", "R", "V", "U"], ["B", "B", "R", "A", "N", "C", "O", "Z", "A"], ["S", "R", "A", "M", "S", "U", "P", "A", "O"], ["A", "A", "B", "A", "P", "O", "T", "Z", "Z"], ["L", "N", "Z", "R", "O", "E", "R", "N", "U"], ["I", "U", "I", "E", "P", "D", "O", "I", "I"], ["L", "O", "L", "L", "O", "R", "A", "C", "A"], ["I", "T", "M", "O", "T", "E", "R", "P", "P"], ["L", "I", "E", "A", "Z", "V", "Y", "U", "U"]], "palavras": ["branco", "preto", "azul", "verde", "rosa", "amarelo", "vermelho", "cinza", "lilas"]}
Then you can read it in in your program with the built-in JSON module:
import json
with open('f.json') as f:
data = json.loads( f.read() )
print data['grelha']
Upvotes: 1