with open('pixels.txt', 'r') as file: for line in file: res = line.strip().split(' ', 1) print(res) xyCoords.append(line.strip())
output : [‘807’, ‘600’] [‘808’, ‘600’] …
xCoords = [] yCoords = [] for i in range(len(xyCoords)): #print(xyCoords[i]) parts = xyCoords[i].split(' ', 1) xCoords.append(parts) parts = xyCoords[i].rsplit(' ', 1) yCoords.append(parts)
output : [‘807’, ‘600’] [‘808’, ‘600’] …
How can I separate the x coordinates from the y coordinates into 2 different lists?
split is working just fine. It splits the string 807 600 on the space. The additional argument 1 tells it to split a maximum of one time, but there’s only one space so this doesn’t change anything. The rsplit version starts on the right side of the string and splits one time. This gets you the same result because again, there’s only one space.
In both cases, it returns a list of substrings, not a single one of those substrings. So if you want to get an x and y coordinate from the line you should index into the result:
parts = line.strip().split(' ', 1) xcoords.append(parts[0]) ycoords.append(parts[1])
Note that if your input file isn’t formatted exactly the way you expect, this might not work.