The most used package to do so is MySQLdb but it's hard to install it using easy_install. Unlike PHP, Only the SQLite driver is installed by default with Python. You must install a MySQL driver before doing anything. os.makedirs("path/to/directory", exist_ok=True) # succeeds even if directory exists.Ĭonnecting to MYSQL with Python 2 in three steps and by allowing a keyword argument to os.makedirs called exist_ok (in 3.2+). Modern versions of Python improve this code quite a bit, both by exposing FileExistsError (in 3.3+). The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation. One option would be to trap the OSError and examine the embedded error code (see Is there a cross-platform way of getting information from Python’s OSError): import os, errnoĪlternatively, there could be a second os.path.exists, but suppose another created the directory after the first check, then removed it before the second one – we could still be fooled.ĭepending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. Unfortunately, blanket-catching OSError and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc. ![]() import osĪs noted in comments and elsewhere, there's a race condition – if the directory is created between the os.path.exists and the os.makedirs calls, the os.makedirs will fail with an OSError. ![]() ![]() Try os.path.exists, and consider os.makedirs for the creation. Path("/my/directory").mkdir(parents=True, exist_ok=True)įor older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it: On Python ≥ 3.5, use : from pathlib import Path
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |