Luka Vlaskalic
Luka Vlaskalic

Reputation: 465

How to create and write into a file correctly in Python

I am trying to create a file in a certain directory, and save the name of that file with today's date.

I am having some issue, where the file is created, but the title line that I want to write in, does not work.

from datetime import datetime
today = datetime.now().date().strftime('%Y-%m-%d')
g = open(path_prefix+today+'.csv', 'w+')
if os.stat(path_prefix+today+'.csv').st_size == 0: # this checks if file is empty
    g = open(path_prefix+today+'.csv', 'w+')
    g.write('Title\r\n')

path_prefix is just a path to the directory I am saving in /Users/name/Documents/folder/subfolder/

I am expecting a file 2019-08-22.csv to be saved in the directory given by path_prefix with a title as specified in the last line of the code above.

What I am getting is an empty file, and if I run the code again then the title is appended into the file.

Upvotes: 0

Views: 69

Answers (3)

Halden Collier
Halden Collier

Reputation: 862

I haven't used Python in a while, but by doing a quick bit of research, this seems like it could work:

# - Load imports
import os
import os.path
from datetime import datetime

# - Get the date
dateToday = datetime.now().date()

# - Set the savePath / path_prefix
savePath = 'C:/Users/name/Documents/folder/subfolder/'
fileName = dateToday.strftime("%Y-%m-%d") # - Convert 'dateToday' to string

# - Join path and file name
completeName = os.path.join(savePath, fileName + ".csv")         

# - Check for file
if (not path.exists(completeName)):
    # - If it doesn't exist, write to it and then close
    with (open(completeName, 'w+') as file):
        file.write('Title\r\n')
else:
    print("File already exists")

Upvotes: 0

Luka Vlaskalic
Luka Vlaskalic

Reputation: 465

As mentioned by @sampie777 I was not losing the file after writing to it, which is why the changes were not being saved when I opened the file. Adding close in an extra line solves the issue that I was having

from datetime import datetime
today = datetime.now().date().strftime('%Y-%m-%d')
g = open(path_prefix+today+'.csv', 'w+')
if os.stat(path_prefix+today+'.csv').st_size == 0: #this checks if file is empty
    g = open(path_prefix+today+'.csv', 'w+')
    g.write('Title\r\n')
    g.close()

I am sure there are plenty of other ways to do this

Upvotes: 1

sampie777
sampie777

Reputation: 133

You need to close the file before the content will be written to it. So call g.close(). I can suggest to use:

with open(path_prefix+today+'.csv', 'w+') as g:
    g.write('...')

This will automatically handle closing the file for you.

Also, why are you opening the file two times?

Tip: I see you are using path_prefix+today+'.csv' a lot. Create a variable for this, so you're code will be a lot easier to maintain. Suggested refactor of the last lines:

output_file_name = path_prefix + today + '.csv'   # I prefer "{}{}.csv".format(path_prefix, today)   or   "%s%s.csv" % (path_prefix, today)
is_output_file_empty = os.stat(output_file_name).st_size == 0

with open(output_file_name, 'a') as output_file:
  if is_output_file_empty:
    output_file.write('Title\r\n')

For more information, see this question: Correct way to write line to file? and maybo also How to check whether a file is empty or not?

Upvotes: 0

Related Questions