lundi 4 mai 2020

if / else in python in order to execute a longer code properly

It seems that i do not understand if else commands. 1. I would like to check if the file test.csv exists 2. If yes, then print ("File exist") and perform the rest of the code 3. Else create a file (check the code below)

How could i define, that in case, that the file test.csv exists do not only print ("File exist"), but also perform the rest of code without the command in "ELSE-Section"?

Now it works like following: Even though the file exist or not the command df = pd.DataFrame(myseries, columns=['values']) is being performed.

import os.path

os.chdir(r"G:\..")
myseries=pd.Series(np.random.randn(5))

if os.path.isfile('test.csv'):
        print ("File exist")
else:
       file = open('test.csv', 'a')
        df = pd.DataFrame(myseries, columns=['values'])
        df.to_csv("test.csv" , index=False)

Rest of code ...

Aucun commentaire:

Enregistrer un commentaire