I"ve created folder and initialized a virtualenv instance in it.
$ mkdir myproject
$ cd myproject
$ virtualenv env
When I run (env)$ pip freeze
, it shows the installed packages as it should.
Now I want to rename myproject/
to project/
.
$ mv myproject/ project/
However, now when I run
$ . env/bin/activate
(env)$ pip freeze
it says pip is not installed. How do I rename the project folder without breaking the environment?
Renaming a virtualenv folder without breaking it mkdir: Questions
mkdir -p functionality in Python
2 answers
Is there a way to get functionality similar to mkdir -p
on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?
Answer #1
For Python ‚â• 3.5, use pathlib.Path.mkdir
:
import pathlib
pathlib.Path("/tmp/path/to/desired/directory").mkdir(parents=True, exist_ok=True)
The exist_ok
parameter was added in Python 3.5.
For Python ‚â• 3.2, os.makedirs
has an optional third argument exist_ok
that, when True
, enables the mkdir -p
functionality—unless mode
is provided and the existing directory has different permissions than the intended ones; in that case, OSError
is raised as previously:
import os
os.makedirs("/tmp/path/to/desired/directory", exist_ok=True)
For even older versions of Python, you can use os.makedirs
and ignore the error:
import errno
import os
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python ‚â• 2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
# possibly handle other errno cases here, otherwise finally:
else:
raise
Answer #2
Renaming a virtualenv folder without breaking it rename: Questions
Rename a dictionary key
5 answers
Is there a way to rename a dictionary key, without reassigning its value to a new name and removing the old name key; and without iterating through dict key/value?
In case of OrderedDict, do the same, while keeping that key"s position.
Answer #1
For a regular dict, you can use:
mydict[k_new] = mydict.pop(k_old)
This will move the item to the end of the dict, unless k_new
was already existing in which case it will overwrite the value in-place.
For a Python 3.7+ dict where you additionally want to preserve the ordering, the simplest is to rebuild an entirely new instance. For example, renaming key 2
to "two"
:
>>> d = {0:0, 1:1, 2:2, 3:3}
>>> {"two" if k == 2 else k:v for k,v in d.items()}
{0: 0, 1: 1, "two": 2, 3: 3}
The same is true for an OrderedDict
, where you can"t use dict comprehension syntax, but you can use a generator expression:
OrderedDict((k_new if k == k_old else k, v) for k, v in od.items())
Modifying the key itself, as the question asks for, is impractical because keys are hashable which usually implies they"re immutable and can"t be modified.
How to rename a file using Python
5 answers
I want to change a.txt
to b.kml
.
Answer #1
Use os.rename
:
import os
os.rename("a.txt", "b.kml")
Rename multiple files in a directory in Python
5 answers
I"m trying to rename some files in a directory using Python.
Say I have a file called CHEESE_CHEESE_TYPE.***
and want to remove CHEESE_
so my resulting filename would be CHEESE_TYPE
I"m trying to use the os.path.split
but it"s not working properly. I have also considered using string manipulations, but have not been successful with that either.
Answer #1
Use os.rename(src, dst)
to rename or move a file or a directory.
$ ls
cheese_cheese_type.bar cheese_cheese_type.foo
$ python
>>> import os
>>> for filename in os.listdir("."):
... if filename.startswith("cheese_"):
... os.rename(filename, filename[7:])
...
>>>
$ ls
cheese_type.bar cheese_type.foo