I am trying to write a Python script that will copy files from one user’s home directory into another user’s home directory. I want it to copy the permissions, as well. I read the Python API and I think that the copy2 method does just that. However, when I run the following code, I get errors.
import shutil
src = raw_input("Please enter a source: ")
dst = raw_input("Please enter a destination: ")
shutil.copy2(src, dst)
The error says:
Traceback (most recent call last):
File "copyfiles.py", line 5, in <module>
shutil.copy2(src, dst)
File "/usr/lib/python2.6/shutil.py", line 99, in copy2
copyfile(src, dst)
File "/usr/lib/python2.6/shutil.py", line 52, in copyfile
fsrc = open(src, 'rb')
IOError: [Errno 2] No such file or directory: '../../../../Desktop/byteswap.c'
Check your current directory using os.getcwd().
Related
My two line code for moving a file into the cwd is as follows:
import os, shutil
shutil.move(os.path.abspath('hello_file.txt'),os.getcwd())
I do have the file just one up the cwd but I get this traceback:
Traceback (most recent call last):
File "<ipython-input-333-f012757a9dca>", line 1, in <module>
shutil.move(os.path.abspath('hello_file.txt'),os.getcwd())
File "/Users/deepayanbhadra/anaconda3/lib/python3.6/shutil.py", line 558, in move
copy_function(src, real_dst)
File "/Users/deepayanbhadra/anaconda3/lib/python3.6/shutil.py", line 257, in copy2
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "/Users/deepayanbhadra/anaconda3/lib/python3.6/shutil.py", line 120, in copyfile
with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: '/Users/deepayanbhadra/Desktop/DIY-Python-Projects/Automating Tasks/hello_file.txt'
The file path you have provided is the current directory. You first have to change to the directory up. One of the ways you can do this is
import os
os.chdir(“..”)
That’s the simplest way but will take you quite a number of lines of code to achieve the same
I am trying to use shutil.copytree to copy a directory onto multiple other directories. I can't get it to work. I'm pretty sure I just need to implement ignore_errors=True, but I cant get it to work. How should I go about implementing 'ignore_errors=True' into
for CopyHere in DeleteThis:
for CopyThis in FilestoCopy:
shutil.copytree(CopyThis, CopyHere)
print('Files have been copied')
My code is as follows:
import shutil
import time
DeleteThis = ['E:', 'F:']
FilestoCopy = ['C:\\Users\\2402neha\\Desktop\\Hehe']
for Directory_to_delete in DeleteThis:
shutil.rmtree(Directory_to_delete, ignore_errors=True)
print('Directories have been wiped')
time.sleep(2)
for CopyHere in DeleteThis:
for CopyThis in FilestoCopy:
shutil.copytree(CopyThis, CopyHere)
print('Files have been copied')
Here are the error messages I get:
Traceback (most recent call last):
File "C:\Users\2402neha\OneDrive\Python\Dis Cleaner\Copy paste test.py", line 17, in <module>
shutil.copytree(CopyThis, CopyHere)
File "C:\Users\2402neha\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 309, in copytree
os.makedirs(dst)
File "C:\Users\2402neha\AppData\Local\Programs\Python\Python35\lib\os.py", line 241, in makedirs
mkdir(name, mode)
PermissionError: [WinError 5] Ingen tilgang: 'E:'
Your destination is E:
The destination directory needs to not exist.
From the documentation for shutil.copytree:
shutil.copytree(src, dst, symlinks=False, ignore=None)
Recursively copy an entire directory tree rooted at src. The destination directory, named by dst, must not already exist; it will be created as well as missing parent directories.
You probably want the directory name you're copying and to join it with the destination:
directory = os.path.basename(CopyThis)
destination = os.path.join(CopyHere, directory)
shutil.copytree(CopyThis, destination)
So I'm fairly new to python and i'm writing a script that needs to untar a file. I use this simple function.
def untar(source_filename, dest_dir):
for f in os.listdir():
print(f)
if(source_filename.endswith("tar.gz") or source_filename.endswith(".tar")):
tar = tarfile.open(source_filename)
tar.extractall(dest_dir)
tar.close()
else:
raise Exception("Could not retrieve .depends for that file.")
I added the initial for loop for debugging purposes. When I invoke it, it prints out the name of the file i need in the current working directory meaning that it does exist. Here is the whole output.
dep.tar.gz
Traceback (most recent call last):
File "init.py", line 70, in <module>
untar('dep.tar.gz', ".")
File "init.py", line 17, in untar
tar = tarfile.open(source_filename)
File "/usr/lib/python3.4/tarfile.py", line 1548, in open
return func(name, "r", fileobj, **kwargs)
File "/usr/lib/python3.4/tarfile.py", line 1646, in bz2open
compresslevel=compresslevel)
File "/usr/lib/python3.4/bz2.py", line 102, in __init__
self._fp = _builtin_open(filename, mode)
FileNotFoundError: [Errno 2] No such file or directory: 'dep.tar.gz'
Can someone tell me how it can see the file in the working directory, and then suddenly not be able to see the file in the working directory?
The program I was using to create the tar placed a space at the beginning of the filename. So python was looking for 'dep.tar.gz' and the actual filename was ' dep.tar.gz'. ty #Ben
TIL - filenames can start with spaces.
I'm beginner in python and I have a problem with this script:
import errno import shutil import os
def copystuff(src, dest):
if os.path.isfile(src):
dest_dirname = os.path.dirname(src)
if not os.path.isdir(dest_dirname):
os.makedirs(dest_dirname)
shutil.copy2(src, dest)
else:
shutil.copytree(src, dest)
copystuff('C:\\Downloads\\index.html', 'J:\\include\\')
Where J it's FlashDriveUSB, and I'm using Python 2.7.
When I'm launching this I got something like that:
C:\Python27>python copy_file.py
Traceback (most recent call last):
File "copy_file.py", line 24, in <module>
copystuff('C:\\Downloads\index.html', 'D:\\include\\')
File "copy_file.py", line 20, in copystuff
shutil.copy2(src, dest)
File "C:\Python27\lib\shutil.py", line 127, in copy2
copyfile(src, dst)
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(dst, 'wb') as fdst:
IOError: [Errno 22] invalid mode ('wb') or filename: 'D:\\include\\'
Please help me.
I resolved my problem. I wanted copy file to folder witch doesn't exist so i added to code a few lines checking if inputted path exists and if not path is created.
I have many files in this folder structure:
test[dir]
-test1 - 123.avi
-video[dir]
-test2 - 123.avi
I want to create folders based based on file names (e.g. test1, test2) in the target dir and move files to respective folders.
I tried this based on code from another thread:
#!/usr/bin/env python
import os, shutil
src = "/home/koogee/Code/test"
dest = "/home/koogee/Downloads"
for dirpath, dirs, files in os.walk(src):
for file in files:
if not file.endswith('.part'):
Dir = file.split("-")[0]
newDir = os.path.join(dest, Dir)
if (not os.path.exists(newDir)):
os.mkdir(newDir)
shutil.move(file, newDir)
I get this error:
Traceback (most recent call last):
File "<stdin>", line 8, in <module>
File "/usr/lib/python2.7/shutil.py", line 299, in move
copy2(src, real_dst)
File "/usr/lib/python2.7/shutil.py", line 128, in copy2
copyfile(src, dst)
File "/usr/lib/python2.7/shutil.py", line 82, in copyfile
with open(src, 'rb') as fsrc:
IOError: [Errno 2] No such file or directory: 'test1'
What is weird is that there is a folder created in /home/koogee/Downloads named 'test1'
When you try to do shutil.move(), your file variable is just the file name with no context of the directory, so it is looking for a file of that name in the script's current directory.
To get an absolute path, use os.path.join(dirpath, file) as the source:
shutil.move(os.path.join(dirpath, file), newDir)