How come that these lines of code creates a folder, but returns an error output? It creates a folder, but doesnt recognize it when calling os.chdir(new_folder).
Updated!
def Gibiru():
id = request.args.get('ID')
key_ = id.split('*')[0] #lfc is the keyword
output_dir = 'Images/Gibiru_pics'
with open('URLS/Gibiru_urls.txt', 'r') as urls:
for url in urls.readlines():
url = url.rstrip("\n")
download_url(url, output_dir, key_)
return str("Success")
def download_url(file_url, output_dir, key_):
print("downloading: ",file_url)
file_name_start_pos = file_url.rfind("/") 1
file_name = file_url[file_name_start_pos:]
r = requests.get(file_url, stream=True)
ts = time.time()
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 %H:%M:%S'))
#os.mkdir(new_folder)
os.makedirs(new_folder)
os.chdir(new_folder)
if r.status_code == requests.codes.ok:
with open(file_name, 'wb') as f:
for data in r:
f.write(data)
The error I'm getting is
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: 'lfc2022-07-25 21:41:55'
When exist_ok = True is applied it creates a folder instead of going inside the folder and working.
CodePudding user response:
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)
CodePudding user response:
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)