How to Copy files with *.ext - python-3.x

source = ('C:\\AutoTransInt\\Input\\oplog\\*.csv')
destination=("C:\\AutoTransInt\\Input\\excel")
How to perform copy operation for above line using
copyfile(source,destination)
i am getting error when i tried to do this

You can use "shutil" that has many methods you can use. One of which is:
from shutil import copyfile
copyfile(src, dst)
you just has to add your source file to src object and destination file to dst object.
Description is as follow:
Copy the contents of the file named src to a file named dst.
The destination location must be writable; otherwise, an IOError exception will be raised.
If dst already exists, it will be replaced.
Special files such as character or block devices and pipes cannot be copied with this function.

you can also use copy2 function of same library.
example:
import shutil
shutil.copy2('/src/dir/file.ext', '/dst/dir/newname.ext') # complete target filename given
shutil.copy2('/src/file.ext', '/dst/dir') # target filename is /dst/dir/file.ext

Related

Moving a folder to itself: shutil, check if file's path is the same as the destination path, if so do nothing

I have the following code which works as expected, expect when the source file is the same as the destination file. I have tried os.path. isfile/isdir/exists but I'm hitting a wall.
So essentially this loops through the file_list and moves the file in the list to the destination. However, it can happen that the source and destination are the same, so, if the file's location is the same as the destination, then it is trying to move itself to itself and obviously fails. So in the following I need to add a check, if the file's location (source) is the same as the destination then pass.
def move_files(file_list, destination):
for file in file_list:
source_file = file
shutil.move(source_file, destination)
In this case the destination is a folder path and the source is a folder path + file name, so I need to ignore the source's file name and compare the path with the destination.
I feel I'm over complicating this, but any help is appreciated.
You can make use of abspath and dirname methods of os.path. The first one returns the absolute path of a directory, the second provides the directory name of a path.
def move_files(file_list, destination):
# just in case you don't provide absolute paths
# you can also consider using `expanduser`
destination = os.path.abspath(destination)
for file in file_list:
file_abs_path = os.path.abspath(file)
if os.path.dirname(file_abs_path) != destination:
shutil.move(file_abs_path, destination)
https://docs.python.org/3/library/os.path.html#os.path.abspath
https://docs.python.org/3/library/os.path.html#os.path.dirname
https://docs.python.org/3/library/os.path.html#os.path.expanduser
I think this is what you want
And also, i've found the source_file variable des nothing special here. So i just ignored it.
import os
import shutil
def move_files(file_list, destination):
dir_lst = os.listdir(destination)
for file in file_list:
if file not in dir_lst: # This will only move the files if its not in the destination folder
shutil.move(file, destination)
For a complete code using only os module,
import os
def move_files(file_list, destination):
dir_lst = os.listdir(destination)
for file in file_list:
if file not in dir_lst: # This will only move the files if its not in the destination folder
os.rename(file, destination)

how to move files from one folder location to other using python

I am creating a automation script and my requirement is to move some files from one folder to another and get it renamed in the meanwhile
I have tried using shutil and os module but none helped me so far
src = r'C:\\Users\\XX\\Downloads\\'
dst = r'C:\\Users\\XX\\Documents\\UIPATH_DUMP\\'
regex = re.compile('MSS_')
files = os.listdir(src)
for i in files:
if regex.match(i):
src1 = src + i
dst1 = dst + i
shutil.move(src1, dst1)
The expected result is my file should get moved to the destination location. I am not able to figure out just how will I rename it? maybe os.rename() would work?
You can use os.rename() to move the file to another path as well as rename it.
For example, if the original file is:
"/Users/billy/d1/xfile.txt"
and you would like to move it to folder "d2" and name it "yfile.txt", you can use the following line of code:
os.rename('/Users/billy/d1/xfile.txt', '/Users/billy/d2/yfile.txt')

Moving all files out from a directory and all its subdirectories

I have a small program that moves all files out of a directory and then searches all subdirectories for other files which it also moves out.
import shutil
import os
import ctypes
import sys
copyfrom = r'D:\Downloads\'
copyto = r'D:\Downloads\'
for r, d, f in os.walk(copyfrom):
for file in f:
if os.path.join(r, file) == copyto:
continue
print(os.path.join(r, file))
shutil.move(os.path.join(r, file), os.path.join(copyto, file))
It works right now but will overwrite every file that has a filename of an existing file. For example if i have banana.mp3 and banana.jpeg it will overwrite one of the files. Instead i would like the file with an existing name to be renamed.
You may check whether the file exists using os.path.exists(destination) . But you should make sure that no race condition is going to happen. So you may open the existing file using a command like os.open(), do your work and then close the file.

python shutil copy the files from source dir to remote dir based on condition

I'm looking to copy the files from source directory to the remote directory using shutil(), however I need to have few checks as follows.
Don't copy the zero byte file to the remote.
If the file is already exits on the remote then don't copy it again unless the file in source has changed contents or updated.
I'm looking for the directory which is of current month, so, traverse to the directory if its available for the current month, like it should be January for the current month.
Importing the modules:
import os
import glob
import shutil
import datetime
Variable to pick the current month:
Info_month = datetime.datetime.now().strftime("%B")
Code snippet:
for filename in glob.glob("/data/Info_month/*/*.txt"):
if not os.path.exists("/remote/data/" + os.path.basename(filename)):
shutil.copy(filename, "/remote/data/")
Above code doesn't take the variable Info_month However, hardcoding the directory name works.
I'm having challenges due to my lack of Python knowledge.
How can I include the variable Info_month into the source dir path?
How to place the check for not to copy zero byte files?
os.path.getsize(fullpathhere) > 0
My rudimentary silly logic:
for filename in glob.glob("/data/Info_month/*/*.txt"):
if os.path.getsize(fullpathhere) > 0 :
if not os.path.exists("/remote/data/" + os.path.basename(filename)):
shutil.copy(filename, "/remote/data/")
else:
pass
Here is a fix of your existing script. This doesn't yet attempt to implement the "source newer than target" logic since you didn't specifically ask about that, and this is arguably too broad already.
for filename in glob.glob("/data/{0}/*/*.txt".format(Info_month)):
# The result of the above glob _is_ a full path
if os.path.getsize(filename) > 0:
# Minor tweak: use os.path.join for portability
if not os.path.exists(os.path.join(["/remote/data/", os.path.basename(filename)])):
shutil.copy(filename, "/remote/data/")
# no need for an explicit "else" if it's a no-op

create a list of files to be deleted

I am working on a search-and-destroy type program which I need it to do is search all directories with a certain file-name and append them to a list. after that delete all those files...not objects in list or the list...
import os
file_list=[]
for root, dirs, files in os.walk(path-to-dir'):
for f_name in files:
if f_name.startswith("file-name"):
file_list.append(f_name)
I could write up to appending part of the code but I don't know next...
Some help please
To remove a file from your computer, use os.remove(). It takes full path to the file as it's parameter, so instead of calling os.remove("infectedFile.dll") you would call os.remove("C:/program files/avira/infectedFile.dll")
So your file_list should contain full paths to the files, and then just call:
for file in file_list:
os.remove(file)
Modify your file_list.append(f_name). The f_name is only a bare name. You need to add the path to the file name in the time of processing, because you do not know where the file was found in the directory hierarchy:
file_list.append(os.path.join(root, f_name))
The root variable contains the path during walking.
To make check whether your code works, just print the content of the list:
print('\n'.join(file_list))
Or you can do it in the loop to get ready for the later part:
for fname in file_list:
print(fname)
Then you just add the os.remove(fname) to remove the file name:
for fname in file_list:
print('removing', fname)
os.remove(fname)

Resources