0

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.

Luka Vlaskalic
  • 445
  • 1
  • 3
  • 19
  • What does `path_prefix` return? – Halden Collier Aug 22 '19 at 10:36
  • path_prefix is just a path to the directory I am saving in `/Users/name/Documents/folder/subfolder/` I don't think this is related, as it saves the file in the right place, and on the second running it finds the file – Luka Vlaskalic Aug 22 '19 at 10:39

3 Answers3

1

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

Luka Vlaskalic
  • 445
  • 1
  • 3
  • 19
0

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?

sampie777
  • 134
  • 6
  • Is the code at the bottom supposed to stand alone? If so, unless I am doing something wrong it does not work. You get a `FileNotFoundError` on the second line, as you never actually create the file. – Luka Vlaskalic Aug 22 '19 at 10:50
  • 1
    Apart from the imports and declarations of `path_prefix` and `today`, you should be able to run it as is. For the `FileNotFoundError`, simply add a check for the existence of the file. You can do that inline, like this: `is_output_file_empty = not os.path.isfile(output_file_name) or os.stat(output_file_name).st_size == 0`. See also this question: https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists-without-exceptions – sampie777 Aug 23 '19 at 07:46
0

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")
Halden Collier
  • 845
  • 7
  • 18
  • 1
    There seems to be a similar problem with this code as with @sampie777 's code, which is that you do not actually create the file, so the if statement raises a `FileNotFoundError` – Luka Vlaskalic Aug 22 '19 at 10:52
  • Edited now, not sure if it will work but let me know. I used `path.exists()` rather than checking the size of a file. – Halden Collier Aug 22 '19 at 11:00