deleting file if it exists; python

You’re trying to delete an open file, and the docs for os.remove() state… On Windows, attempting to remove a file that is in use causes an exception to be raised You could change the code to… …or you can replace all that with… …which will truncate the file to zero length before opening.

How to delete a file or folder in Python?

os.remove() removes a file. os.rmdir() removes an empty directory. shutil.rmtree() deletes a directory and all its contents. Path objects from the Python 3.4+ pathlib module also expose these instance methods: pathlib.Path.unlink() removes a file or symbolic link. pathlib.Path.rmdir() removes an empty directory.

How to uninstall pip on OSX?

The first thing you should try is: On many environments that doesn’t work. So given the lack of info on that problem, I ended up removing pip manually from /usr/local/bin.

How to read a large file – line by line?

The correct, fully Pythonic way to read a file is the following: The with statement handles opening and closing the file, including if an exception is raised in the inner block. The for line in f treats the file object f as an iterable, which automatically uses buffered I/O and memory management so you don’t … Read more

How do I check what version of Python is running my script?

This information is available in the sys.version string in the sys module: Human readable: For further processing, use sys.version_info or sys.hexversion: To ensure a script runs with a minimal version requirement of the Python interpreter add this to your code: This compares major and minor version information. Add micro (=0, 1, etc) and even releaselevel … Read more

Using global variables in a function

You can use a global variable within other functions by declaring it as global within each function that assigns a value to it: I imagine the reason for it is that, since global variables are so dangerous, Python wants to make sure that you really know that’s what you’re playing with by explicitly requiring the … Read more

bash: pip: command not found

Why not just do sudo easy_install pip or if this is for python 2.6 sudo easy_install-2.6 pip? This installs pip using the default python package installer system and saves you the hassle of manual set-up all at the same time. This will allow you to then run the pip command for python package installation as it will be installed with … Read more

Relative imports – ModuleNotFoundError: No module named x

TL;DR: You can’t do relative imports from the file you execute since __main__ module is not a part of a package. Absolute imports – import something available on sys.path Relative imports – import something relative to the current module, must be a part of a package If you’re running both variants in exactly the same way, one of them should work. Here is … Read more

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