Reputation: 119
I am trying to use python to make a file that takes in the date and then creates a file with it. This program is going to run all day every day and every new day I want a new file to be made with that day date and then for the file to be used. I don't get why my code will not allow that to work.
The code shows that if the file does not open it will get a FileNotFoundError
and then I have it make the file but it seems to not be making the time. However if I take {date}
out it will make the file.
I've tested if it is {date}
and it seems to be it but it is a string so I don't get it
import time
import csv
timestr = time.localtime() # get time
date= time.strftime("%m/%d/%Y", timestr)
filename = (f"Readings/Readings{date}.csv")
try:
f = open(filename, 'r')
except FileNotFoundError:
print("File not found, making file")
with open(filename, 'w+') as file_object:
writer = csv.writer(file_object)
writer.writerow(['Test'])
file_object.close()
else:
print('yes')
Error:
Exception has occurred: FileNotFoundError
[Errno 2] No such file or directory: 'Readings/Readings09/18/2019.csv
File "/home/pi/Desktop/script/script.py", line 17, in <module> with open(filename, 'w+') as file_object:
File "/usr/lib/python3.7/runpy.py", line 85, in _run_code exec(code, run_globals)
File "/usr/lib/python3.7/runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name)
File "/usr/lib/python3.7/runpy.py", line 263, in run_path pkg_name=pkg_name, script_name=fname)
Upvotes: 0
Views: 308
Reputation: 1
get rid of the / in the date part: change this: "%m/%d/%Y" to "%m-%d-%Y"
Upvotes: 0
Reputation: 3061
Because the date you're using contains slashes "/
". You can try to use os.makedirs(os.path.dirname(filename), exist_ok=True)
, to create the subfolder before creating the file.
Upvotes: 0
Reputation: 4260
Make sure you have a Reading folder or Create one using os.makedirs
import time
import csv
timestr = time.localtime() # get time
date= time.strftime("%m/%d/%Y", timestr).replace('/','_')
filename = (f"Readings/Readings{date}.csv")
try:
f = open(filename, 'r')
except FileNotFoundError:
print("File not found, making file")
with open(filename, 'w+') as file_object:
writer = csv.writer(file_object)
writer.writerow(['Test'])
file_object.close()
else:
print('yes')
Upvotes: 1