I have a .csv file that has this structure:
X310.433,Y9.6
X310.54,Y10
X143.52
X144.77
when there is no "X" or "Y" value in a line, I want to take the value from the line above and copy it to the line after that, that is missing the value. For this example copy the Y10 into the next line, and seperate it with a comma. How can i do this with python?
Without any utility modules you could do this:
Let's assume that the file content is:
X310.433,Y9.6
Y999
X310.54,Y10
X143.52
X144.77
...then...
lines: list[tuple[str, str]] = []
with open("foo.csv") as foo:
for line in map(str.strip, foo):
if line:
a, *b = line.split(",")
if a[0] == "X":
if b:
lines.append((a, b[0]))
else:
lines.append((a, lines[-1][1]))
else:
assert a[0] == "Y"
if b:
lines.append((b[0], a))
else:
lines.append((lines[-1][0], a))
for line in lines:
print(",".join(line))
Output:
X310.433,Y9.6
X310.433,Y999
X310.54,Y10
X143.52,Y10
X144.77,Y10
Note:
If the first line of the file contains either one of X or Y (but not both) this will fail
EDIT:
More robust version that rewrites the original file:
with open("foo.csv", "r+") as foo:
lines: list[tuple[str, str]] = []
for line in map(str.strip, foo):
if line:
a, *b = line.split(",")
if a.startswith("X"):
y = b[0] if b else lines[-1][1]
lines.append((a, y))
elif a.startswith("Y"):
x = b[0] if b else lines[-1][0]
lines.append((x, a))
foo.seek(0)
for line in lines:
print(",".join(line), file=foo)
foo.truncate()
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