0

How come that these lines of code creates a folder, but returns an error output?

key_ = "Test"
new_folder = os.makedirs(str(key_)+str(datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M')))
os.chdir(str(new_folder))

Folder

The error I'm getting is

line 457, in download_url
os.chdir(str(new_folder))
FileNotFoundError: [Errno 2] No such file or directory: 'None'
nullptr
  • 3,701
  • 2
  • 16
  • 40
AnxiousDino
  • 187
  • 15
  • 1
    I'd advise not to put '/' or '\' in file or directory names as moving between Windows & Unix, it will fail. – Bib Jul 25 '22 at 19:29

2 Answers2

2

os.makedirs() doesn't return the name of the directory it created. Assign the directory name to a variable first, and use that in both function calls.

key_ = "Test"
new_folder = str(key_)+str(datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M'))
os.makedirs(new_folder, exist_ok=True)
os.chdir(new_folder)
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I still be getting an error saying --------> File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py", line 225, in makedirs mkdir(name, mode) FileExistsError: [Errno 17] File exists: 'Test2022-07-25 21:41:55' – AnxiousDino Jul 25 '22 at 19:44
  • Use the `exist_ok = True` option to prevent errors if the directory already exists. – Barmar Jul 25 '22 at 19:53
0

This seems to be the solution:

file_path = os.path.realpath(__file__)
output_files = file_path.replace('billede_indsamling.py',str(output_dir))
os.chdir(output_files)
new_folder = str(key_)+str(datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d'))
#os.mkdir(new_folder) 
path = os.path.join(output_files, new_folder)

if not os.path.exists(path):
    os.makedirs(path)
    print("Directory '%s' created successfully" %new_folder)
elif os.path.exists(path):
    os.chdir(path)
AnxiousDino
  • 187
  • 15