I have a script that I will run multiple times, and the first line in the main function of this script is something like this:
def main():
users_csv_file_init()
What this function should do is to create a CSV file and append the columns' names, if such file doesn't exist, and if it does, it should do nothing. What I wrote was this:
def users_csv_file_init():
with open("users.csv", 'a+') as output_file:
writer = csv.writer(output_file)
writer.writerow(["userid", "username", "fname", "lname", "uuid"])
This fails, because it creates a new row (the columns' names) every time I run the script, and it makes sense, because a+
creates the file if it doesn't exist and open it in append mode. But I can't change to w+
either, because that deletes everything that was previously in the file. And from the modes of open()
, only w+
and a+
seem to create the file if it doesn't exist.
I could manually check if the file exists, like this:
def users_csv_file_init():
if not os.path.exists("users.csv"):
with open("users.csv", 'w') as output_file:
writer = csv.writer(output_file)
writer.writerow(["userid", "username", "fname", "lname", "uuid"])
But I'm told it's unpythonic and prone to race conditions to do it like this. How can I do it properly?