Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python read in string from file and split it into values [closed]

Tags:

python

file

split

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!

like image 561
Paul Avatar asked Mar 25 '12 03:03

Paul


People also ask

How do you read and split a text file in Python?

Example 1: Using the splitlines() the read() method reads the data from the file which is stored in the variable file_data. splitlines() method splits the data into lines and returns a list object. After printing out the list, the file is closed using the close() method.

How do you split data in a string in Python?

Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.


1 Answers

Something like this - for each line read into string variable a:

>>> a = "123,456"
>>> b = a.split(",")
>>> b
['123', '456']
>>> c = [int(e) for e in b]
>>> c
[123, 456]
>>> x, y = c
>>> x
123
>>> y
456

Now you can do what is necessary with x and y as assigned, which are integers.

like image 113
icyrock.com Avatar answered Sep 30 '22 19:09

icyrock.com