I'm trying to move a file but it won't work. It keeps giving the error "Errno 2: File or directory does not exist". The code is shown below
import shutil
original = '%userprofile%/Desktop/Test'
New = '%userprofile%/Desktop/Test2'
shutil.move(original, New)
if anyone has any advice on how to solve this please help me.
You can use os.path.expandvars to expand the %userprofile% variable and the resultant path can be passed into the shutil.move API.
>>> help(os.path.expandvars)
Help on function expandvars in module ntpath:
expandvars(path)
Expand shell variables of the forms $var, ${var} and %var%.
Unknown variables are left unchanged.
ie,
shutil.move(os.path.expandvars(original), os.path.expandvars(New))
If %userprofile% is the only variable you need, it can be done with pathlib.Path.expanduser as such:
import shutil
from pathlib import Path
original = Path('~/Desktop/Test').expanduser()
New = Path('~/Desktop/Test2').expanduser()
shutil.move(original, New)
Related
I have a script that creates a folder foo-12345. Issue is, the numbers in the folder change name anytime I run a per script that creates it. I'm trying to find a way to change directory into the folder so I can do a search. I tried using a variable:
import os
output = /var/foo-*
os.chdir(ouput)
This does not seem to work. Is there a way to capture that folder name in a variable and use that variable instead?
You can use the glob module to do it.
import glob
dirs = glob.glob('/var/foo-*')
The resulting dirs is a list, so you will need to process it as such. Have a look at the documentation
I am trying to access a text file in the parent directory,
Eg : python script is in codeSrc & the text file is in mainFolder.
script path:
G:\mainFolder\codeSrc\fun.py
desired file path:
G:\mainFolder\foo.txt
I am currently using this syntax with python 2.7x,
import os
filename = os.path.dirname(os.getcwd())+"\\foo.txt"
Although this works fine, is there a better (prettier :P) way to do this?
While your example works, it is maybe not the nicest, neither is mine, probably. Anyhow, os.path.dirname() is probably meant for strings where the final part is already a filename. It uses os.path.split(), which provides an empty string if the path end with a slash. So this potentially can go wrong. Moreover, as you are already using os.path, I'd also use it to join paths, which then becomes even platform independent. I'd write
os.path.join( os.getcwd(), '..', 'foo.txt' )
...and concerning the readability of the code, here (as in the post using the environ module) it becomes evident immediately that you go one level up.
To get a path to a file in the parent directory of the current script you can do:
import os
file_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'foo.txt')
You can try this
import environ
environ.Path() - 1 + 'foo.txt'
to get the parent dir the below code will help you:
import os
os.path.abspath(os.path.join('..', os.getcwd()))
I am trying to make a program that will go through and visit an array of directories and run a program and create a file inside.
I have everything working except that I need to figure out a way to import from a new path each time to get to a new directory.
For example:
L =["directory1", "directory2", "directory3"]
for i in range(len(L)):
#I know this is wrong, but just to give an idea
myPath = "parent."+L[i]
from myPath import file
#make file... etc.
Obviously when I use myPath as a variable for the path to import, I get an error. I have tried several different ways by searching online through Stack Overflow and reading OS and Sys documentation, but have come to no working result.
You can use 'imp' module to load source code of python scrips
import imp
root_dir = '/root/'
dirs =["directory1", "directory2", "directory3"]
for _dir in dirs:
module_path = os.path.join(root_dir,_dir,'module.py')
mod = imp.load_source("module_name", module_path)
# now you can call function in regular way, like mod.some_func()
I want to create a text file inside each directory. To do this I must
cycle through my array and take each directory name so I can visit it.
import is for loading external modules, not creating new files, if creating new files is what you want to do, use the open statement, and open the not yet existing file with 'w' mode. Note: the directory must exist.
from os.path import join
L =["directory1", "directory2", "directory3"]
for d in L: # loop through the directories
with open(join(d,"filename.txt"), "w") as file:
pass # or do stuff with the newly created file
Within in my script it's very rare that I run into this problem where I'm trying to move a file to this new folder that already happens to have a file with the same name, but it just happened. So my current code uses the shutil.move method but it errors out with the duplicate file names. I was hoping I could use a simple if statement of checking if source is already in destination and change the name slightly but can't get to that work either. I also read another post on here that used the distutils module for this issue but that one gives me an attribute error. Any other ideas people may have for this?
I added some sample code below. There is already a file called 'file.txt' in the 'C:\data\new' directory. The error given is Destination path already exist.
import shutil
myfile = r"C:\data\file.txt"
newpath = r"C:\data\new"
shutil.move(myfile, newpath)
You can just check that the file exists with os.path.exists and then remove it if it does.
import os
import shutil
myfile = r"C:\data\file.txt"
newpath = r"C:\data\new"
# if check existence of the new possible new path name.
check_existence = os.path.join(newpath, os.path.basename(myfile))
if os.path.exists(check_existence):
os.remove(check_existence)
shutil.move(myfile, newpath)
In Python 3.4 you can try the pathlib module. This is just an example so you can rewrite this to be more efficient/use variables:
import pathlib
import shutil
myfile = r"C:\data\file.txt"
newpath = r"C:\data\new"
p = pathlib.Path("C:\data\new")
if not p.exists():
shutil.move(myfile, newpath)
#Use an else: here to handle your edge case.
Probably a simple query.. But basically, I have data in directory "/foo/bar/foobar.txt"
and I am working in directory "/some/path/read_foobar.py"..
Now I want to read the file "foobar.txt" but rather than giving full path, I thought of adding /foo/bar/ to the path..
So, added the following at the start of read_foobar.py
import sys
sys.path.append("/foo/bar")
But when I try to read open("foobar.txt","r"), it is not able to find the file?
how do I do this?
Thanks
You can do it like this:
import os
os.chdir('/foo/bar')
f = open('foobar.txt', 'r')
sys.path is used to set the path used to look for python modules. Short of you writing some helper function that has a list of directories to search in when opening a file, I don't believe there is a standard module that provides this functionality.
From what I gathered from here and some quick tests, appending a path to sys.path will make python search in that path when you import a file/module, but not when open-ing it. Let's say we have a file called foo.py in /foo/bar/
import sys
sys.path.append("/foo/bar/")
try:
f = open('foo.py', 'r')
except:
print('this did not work') # this will print
import foo # no problems here
Unfortunately you can't. The PATH environment variable is only used by the operating system to search for executable files, and python uses it (along with the environment variable PYTHONPATH) to search for python modules to import.
You may want to consider setting a symbolic link to that file from your current working directory
ln -s /foo/bar/foobar.txt /some/path/foobar.text