Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add the "X" or "Y" value from a line above to the line that is missing the value?

Tags:

python

csv

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?

like image 242
volk.SWAG.en Avatar asked Dec 20 '25 14:12

volk.SWAG.en


1 Answers

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()
like image 136
Ramrab Avatar answered Dec 23 '25 02:12

Ramrab