How to read line by line and parse from a file in python?
I am new to python.
The first line of input is the number of simulations.
The next line is the number of rows(x), followed by a single space, and followed by number of columns (y).
The next group of y lines will have x number of characters, with a single period (‘.’) representing a blank space and a single capitol “A” representing a starting Agent.
My code got an error
Traceback (most recent call last):
numSims = int (line)
TypeError: int() argument must be a string or a number, not 'list'
Thanks for your help.
Input.txt
2 --- 2 simulations
3 3 -- 3*3 map
.A. --map
AA.
A.A
2 2 --2*2 map
AA --map
.A
def main(cls, args):
numSims = 0
path = os.path.expanduser('~/Desktop/input.txt')
f = open(path)
line = f.readlines()
numSims = int (line)
print numSims
k=0
while k < numSims:
minPerCycle = 1
row = 0
col = 0
xyLine= f.readLines()
row = int(xyLine.split()[0])
col = int(xyLine.split()[1])
myMap = [[Spot() for j in range(col)] for i in range(row)]
## for-while
i = 0
while i < row:
myLine = cls.br.readLines()
## for-while
j = 0
while j < col:
if (myLine.charAt(j) == 'B'):
cls.myMap[i][j] = Spot(True)
else:
cls.myMap[i][j] = Spot(False)
j += 1
i += 1
For Spot.py
Spot.py
class Spot(object):
isBunny = bool()
nextCycle = 0
UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3
SLEEP = 4
def __init__(self, newIsBunny):
self.isBunny = newIsBunny
self.nextCycle = self.UP
Your errors are numerous, here are the ones I’ve found so far:
The line
numSims = (int)linedoes not do what you think it does. Python does not have C casts, you need to call theinttype instead:You compound this error later on by using an uppercase spelling of
Int:Correct these in a similar manner:
and since the default for
.split()is to split on whitespace you can leave out the" "argument. Better yet, combine them into one line:You never increment
k, so yourwhile k < numSims:loop will continue forever, so you’ll get an EOF error. Use aforloop instead:You don’t need to use
whileanywhere in this function, they can all be replaced withfor variable in xrange(upperlimit):loops.Python strings have no
.charAtmethod. Use[index]instead:but since
myLine[j] == 'A'is a boolean test, you can simplify yourSpot()instantiation like so:There is no need to initialize variables quite so much in Python. You can get of most of the
numSims = 0andcol = 0lines, etc. if you are assigning a new value on a following line.You create a ‘myMap
variable but then ignore it by referring tocls.myMap` instead.There is no handling of multible maps here; the last map in the file would overwrite any preceding map.
Rewritten version: