Is it safe to use os.environ.setdefault?

The os.environ documentation does state it’s a mapping: A mapping object representing the string environment. As such it behaves according to the python mapping documentation of which dict is the standard implementation. os.environ therefor behaves just like the standard dict, it has all the same methods: >>> import os >>> len(os.environ) 36 >>> ‘USER’ in … Read more

get script directory name – Python [duplicate]

import os os.path.basename(os.path.dirname(os.path.realpath(__file__))) Broken down: currentFile = __file__ # May be ‘my_script’, or ‘./my_script’ or # ‘/home/user/test/my_script.py’ depending on exactly how # the script was run/loaded. realPath = os.path.realpath(currentFile) # /home/user/test/my_script.py dirPath = os.path.dirname(realPath) # /home/user/test dirName = os.path.basename(dirPath) # test

How do I move a file in Python?

os.rename(), os.replace(), or shutil.move() All employ the same syntax: import os import shutil os.rename(“path/to/current/file.foo”, “path/to/new/destination/for/file.foo”) os.replace(“path/to/current/file.foo”, “path/to/new/destination/for/file.foo”) shutil.move(“path/to/current/file.foo”, “path/to/new/destination/for/file.foo”) The filename (“file.foo”) must be included in both the source and destination arguments. If it differs between the two, the file will be renamed as well as moved. The directory within which the new file is … Read more

How to get folder name, in which given file resides, from pathlib.path?

It looks like there is a parents element that contains all the parent directories of a given path. E.g., if you start with: >>> import pathlib >>> p = pathlib.Path(‘/path/to/my/file’) Then p.parents[0] is the directory containing file: >>> p.parents[0] PosixPath(‘/path/to/my’) …and p.parents[1] will be the next directory up: >>> p.parents[1] PosixPath(‘/path/to’) Etc. p.parent is another … Read more

How to move a file in Python?

os.rename(), os.replace(), or shutil.move() All employ the same syntax: import os import shutil os.rename(“path/to/current/file.foo”, “path/to/new/destination/for/file.foo”) os.replace(“path/to/current/file.foo”, “path/to/new/destination/for/file.foo”) shutil.move(“path/to/current/file.foo”, “path/to/new/destination/for/file.foo”) Note that you must include the file name (file.foo) in both the source and destination arguments. If it is changed, the file will be renamed as well as moved. Note also that in the first two … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)