Search code examples
pythoncsvline

Python, write a new line in a CSV-File


I'm working on a Python-Script which takes some weather information from a Website and put it in a CSV-File every day.

I want to append the new information below and not directly behind it.

This is my CSV-Append-Function:

def save_data(weatherdatasaved):
filename = "weather.csv"
header="Datum;Luft-Min;Luft-Max;Durchschn.Wassertemp;Barometer"+"\n"
#Check whether the file exists
if(os.path.exists(os.path.expanduser(filename))==False):
    file = open(os.path.expanduser(filename),"wb")
    file.write(bytes(header, encoding="ascii",errors="ignore"))
    file.close()

file = open(os.path.expanduser(filename),"a")
i=0
while (i < len(weatherdatasaved)):
    if((i+1)==len(weatherdatasaved):
       file.write(weatherdatasaved[i]+"\n")
    else:
        file.write(weatherdatasaved[i]+";")
    i+=1
file.close()

What I Get:

Datum;Luft-Min;Luft-Max;Durchschn.Wassertemp;Barometer01.11.2016;9.5;6.8;12;1023.2

What I want:

Max;Durchschn.Wassertemp;Barometer

01.11.2016;9.5;6.8;12;1023.2

Can someone help me? Thanks a lot.


Solution

  • In order to work with different OS, you can use the os.linebreak attribute. For example:

    import os
    
    multiline = 'line 1' + os.linesep + 'line 2'
    

    In your case replace all \n with os.linesep.