I have a txt file that looks like this:
1, 0., 0., 0.
2, 0., 0., 600.
3, 0., 0., 2600.
4, 0., 0., 50.
I'd like to read it and create the following list:
['1', '0', '0', '0']
['2', '0', '0', '600']
['3', '0', '0', '2600']
['4', '0', '0', '50']
However I only manage to obtain:
['1', '0.', '0.', '0.']
['2', '0.', '0.', '600.']
['3', '0.', '0.', '2600.']
['4', '0.', '0.', '50.']
My code looks like:
for line in inputFile:
fileData.append([x.strip() for x in line.split(',')])
EDIT: How can I convert my list of strings into a list of integers? tried some variations using the line of code I wrote above but couldn't make it.
Pass "." + string.whitespace to strip so that it strips both the spaces and the periods:
from string import whitespace
for line in inputFile:
fileData.append([int(x.strip("." + whitespace)) for x in line.split(',')])
for line in inputFile:
fileData.append([int(x.strip().rstrip('.')) for x in line.split(',')])
Instead of x.strip().rstrip('.'), you could use x.strip(' \t\r\n.'), but I think it is cleaner to let x.strip() handle all of the whitespace.
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