Search code examples
pythonheader-files

Python change headerrow of textfile (.csv)


I have a txt file where the headerrow is incorrect. How do I replace the headerrow with the correct one?

old_header = "1;2;3;4;5;"
new_header = "1;2;3;4;5;6;7;8"

If I read the file with I don't get the first line.

    with open(full_path) as file:
        first_line = file.readline()

enter image description here

CompanyNumber;AccountingYear;Schema;RAT001;RAT002;RAT003;RAT004;RAT005;RAT006;RAT007;RAT008;RAT009;RAT010;RAT011;RAT012;RAT013;RAT014;RAT015;RAT016;RAT017;RAT018;RAT019;RAT020;RAT021;RAT101;RAT102;RAT103;RAT104;RAT105;RAT106;RAT107;RAT108;RAT109;RAT110;RAT111;RAT112;RAT113;RAT114;RAT115;RAT116;RAT117;RAT118;RAT119;RAT120;RAT121;RAT125;RAT127;RAT201;RAT202;RAT203;RAT204;RAT205;RAT206;RAT207;RAT208;RAT209;RAT210;RAT211;RAT212;RAT213;RAT214;RAT217;RAT218;RAT219;RAT220;RAT221
9999999999;2020;Abbreviated with capital;;;;;;;;;;;;;;;;;;;;;;;;;;;;-10.7;0.33;-1.57;-3.8;-3.74;-1.5;;;;;;;100;;;;;;;;;;;;;;;;;;;;;;;
8888888888;2020;Full with capital;11.16;8.34;90.25;67804.74;80.92;87.52;3.97;0.16;15.22;20.41;12.65;9.48;1.67;2;;;4.82;91.32;61.21;8.94;17.06;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Red: headerrow where there needs to be added ;x1;x2;x3


Solution

  • read the file, strip the end of line character, add the needed part to the first line, write new file (with new EOL characters)

    with open("data.csv") as infile:
        data = infile.read().splitlines()
    
    data[0] = data[0] + ";x1;x2;x3"
    
    with open("outfile.csv", "w") as outfile:
        for line in data:
            outfile.write(line+"\n")