在python中,第一次创建文件夹时,会创建目录并在该文件夹路径中成功创建文件。当再次需要在同一位置创建新文件时,我收到此错误:
[Errno 17] File exists: '/home/test/files/tweets/'.
请问有什么建议吗?
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")
最佳答案
使用 try:except:
捕获 OSError
:
try:
os.mkdir(new_folder, 0755)
except OSError:
pass
这有点令人不满意,因为还有其他错误可能会被忽略。
关于Python [Errno 17] 文件存在问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46149537/