Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python [Errno 17] File exists Issue

In python, When the folder is created first time, The directory is created and the files are successfully created in that folder path. When again a new file needs to be created in the same location, I'm getting this error:

[Errno 17] File exists: '/home/test/files/tweets/'.

Any suggestions please?

if len(downloadedfile) > 0:
    #insert_time=time.strftime('%Y_%-m_%-d')
    #download_path='/home/test/files/tweets/'
    #file_path= download_path+insert_time+"/"+hashes
    #print(file_path)
    now = datetime.now
    new_folder = '/home/test/files/tweets/{}'.format(now().strftime('%Y_%-m_%-d'))
    os.mkdir(new_folder, 0755 );
    folder_path = new_folder+"/"+hashes
    fo = open(folder_path,"wb")
    fo.write(downloadedfile)
    fo.close()
    print("File Downloaded")
else:
   print("File Not Downloaded")
like image 575
Arun Avatar asked Oct 23 '25 03:10

Arun


1 Answers

Catch the OSError with a try:except::

try:
    os.mkdir(new_folder, 0755)
except OSError:
    pass

This is a bit unsatisfactory, as there are other errors that this might ignore.

like image 135
David Jones Avatar answered Oct 24 '25 16:10

David Jones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!