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.

2
  • What does path_prefix return? Commented Aug 22, 2019 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 Commented Aug 22, 2019 at 10:39

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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?

2 Comments

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.
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: stackoverflow.com/questions/82831/…
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")

2 Comments

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
Edited now, not sure if it will work but let me know. I used path.exists() rather than checking the size of a file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.