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!
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With