I have a file in the format below:
995957,16833579
995959,16777241
995960,16829368
995961,50431654
I want to read in each line but split the values into the appropriate values. For example the first line would be split into:
x = 995957
y = 16833579
Since its a string when you read it in and I want to convert them to an int and split them, how exactly would I go about doing this? Any help would be appreciated.
Thanks!
I would do something like:
filename = "mynumbers.txt"
mynumbers = []
with open(filename) as f:
for line in f:
mynumbers.append([int(n) for n in line.strip().split(',')])
for pair in mynumbers:
try:
x,y = pair[0],pair[1]
# Do Something with x and y
except IndexError:
print "A line in the file doesn't have enough entries."
The with open is recommended in http://docs.python.org/tutorial/inputoutput.html since it makes sure files are closed correctly even if an exception is raised during the processing.
>>> [[int(i) for i in line.strip().split(',')] for line in open('input.txt').readlines()]
[[995957, 16833579], [995959, 16777241], [995960, 16829368], [995961, 50431654]]
Use open(file, mode)
for files.
The mode is a variant of 'r' for read, 'w' for write, and possibly 'b' appended (e.g., 'rb') to open binary files. See the link below.
Use open
with readline()
or readlines()
. The former will return a line at a time, while the latter returns a list of the lines.
Use split(delimiter)
to split on the comma.
Lastly, you need to cast each item to an integer: int(foo)
. You'll probably want to surround your cast with a try block followed by except ValueError
as in the link below.
You can also use 'multiple assignment' to assign a and b at once:
>>>a, b = map(int, "2342342,2234234".split(","))
>>>print a
2342342
>>>type(a)
<type 'int'>
Source: Stackoverflow.com