I am trying to copy a word file from an existing folder and copying it to a new output folder. In this output folder, I have again created different folders as per the user id and inside this the word file should be placed for every user. However, while copying this, I am facing an issue as the id folder is interpreted as
a file. The output file picture is attached here:
I am using the shutil module for this and the code which I wrote is:
id = tup2[i]
shutil.copy('C:\\Python27\\mydoc.docx', ('C:\\Python27\\Output\\%s') %(id))
that's expected. If the destination folder exists, then copy appends the basename of your file and copies the file into the destination folder.
Copies the file src to the file or directory dst. src and dst should be strings. If dst specifies a directory, the file will be copied into dst using the base filename from src.
If it doesn't, then copy assumes that you want to copy and change the name (the unix cp commands works exactly the same).
A workaround would be to create the directory beforehand/ensure it's here:
import os,shutil
output_dir = os.path.join(r'C:\Python27\Output',str(id))
if not os.path.isdir(output_dir):
os.mkdir(output_dir)
shutil.copy(r'C:\Python27\mydoc.docx', output_dir)
(it's also better to use proper path handling functions from os.path and raw strings for litteral windows paths)
Related
this might be a silly question but I'm struggling a lot finding solution to it.
So I have a file in the given folder:
Output\20190101_0100\20190101_0100.csv
Now I want to zip the file and save it to same location. So here's my try:
zipfile.ZipFile('Output/20190101_0100/20190101_0100_11.zip', mode='w', compression=zipfile.ZIP_DEFLATED).write('Output/20190101_0100/20190101_0100_11.csv')
But it's making a folder insider zip folder and saving it, as shown below:
Output\20190101_0100\20190101_0100_11.zip\Output\20190101_0100\20190101_0100_11.csv
Can someone tell me how can I save my file directly in the same location or location mentioned below:
Output\20190101_0100\20190101_0100_11.zip\20190101_0100_11.csv
Rephrasing of question
The question is slightly confusing because Output\20190101_0100\20190101_0100_11.zip\Output\20190101_0100\20190101_0100_11.csv won't be a file, but rather Output\20190101_0100\20190101_0100_11.csv will be a file within the zip file Output\20190101_0100\20190101_0100_11.zip (if I am not mistaken)
Just to restate your problem (if I understood it correctly):
You have a file Output\20190101_0100\20190101_0100.csv (a file 20190101_0100.csv in the Output -> 20190101_0100 sub directory)
You want to create the zip file Output/20190101_0100/20190101_0100_11.zip (20190101_0100_11.zip in the Output -> 20190101_0100.zip directory)
You want to add the aforementioned CSV file Output\20190101_0100\20190101_0100.csv but without the leading path, i.e. as 20190101_0100_11.csv rather than Output\20190101_0100\20190101_0100.csv.
Or to not get confused with too many similar directories, let's simplify it as:
You have a file test.csv in the sub directory sub-folder
You want to create the zip file test.zip
You want to add the aforementioned CSV file test.csv but without the leading path, i.e. as test.csv rather than sub-folder/test.csv.
Answer
From the ZipFile.write documentation:
Write the file named filename to the archive, giving it the archive
name arcname (by default, this will be the same as filename, but
without a drive letter and with leading path separators removed).
That means that arcname will default to the passed in filename (it doesn't have a drive letter or leading path separator).
If you want to remove the sub folder part, just pass in arcname as well. e.g.:
import zipfile
with zipfile.ZipFile('path-to-zip/test.zip', 'w') as zf:
zf.write('sub-folder/test.csv', arcname='test.csv')
You could try using a raw path:
zipfile.ZipFile('Output/20190101_0100/20190101_0100_11.zip', mode='w', compression=zipfile.ZIP_DEFLATED).write(r'C:\...\Output\20190101_0100\20190101_0100_11.csv')
I am trying to zip contents of the src folder and save the zip file in the dst folder:
import shutil
src = '/home/bart/python_projects/testenv/sampler_proj/sampler/media/audio/slices/'
dst = '/home/bart/python_projects/testenv/sampler_proj/sampler/media/audio/zipped/'
shutil.make_archive('samples', 'zip', base_dir=src, root_dir=dst)
However, the samples.zip file is not being saved to the dst folder, but to the folder in which my script resides, that is /home/bart/python_projects/testenv/sampler_proj/sampler/media/audio/.
How can I fix it?
I have looked at some other SO threads and the shutil docs, but the definitions of root_dir and base_dir are quite confusing.
According to the docs:
shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]])
Create an archive file (such as zip or tar) and return its name.
base_name is the name of the file to create, including the path, minus any format-specific extension. format is the archive format: one of “zip” (if the zlib module is available), “tar”, “gztar” (if the zlib module is available), “bztar” (if the bz2 module is available), or “xztar” (if the lzma module is available).
(enphasis in bold is mine).
The first argument should include the full destination path, if you do not want the file to be in your current directory.
So you are assigning a wrong directory to root_dir I guess. According to the docs, root_dir should be:
root_dir is a directory that will be the root directory of the archive; for example, we typically chdir into root_dir before creating the archive.
Try to do:
src = '/home/bart/python_projects/testenv/sampler_proj/sampler/media/audio/slices/'
dst = '/home/bart/python_projects/testenv/sampler_proj/sampler/media/audio/zipped/'
pth = os.path.join(dst, 'samples')
shutil.make_archive(pth, 'zip', root_dir=src, base_dir=src)
In most cases, root_dir and base_dir are the same directory, the one that you want to archive. It make a sense to provide both of them for more complex cases, which does not seem your case. For example, if you want to go into a directory, and then create separate archives of subdirectories through recursion.
This question already has answers here:
How to copy files
(25 answers)
Closed 5 years ago.
I have the path of a file stored in a variable (say) filePath. I would like to copy that particular file to another specific folder within a Python script.
I tried
folderPath = (os.getcwd() + "/folder_name/") #to get the path of the folder
shutil.copyfile(filePath, folderPath)
But I got an error IOError: [Errno 21] Is a directory.
How can I solve this ?
My question might seem to be a duplicate of How do I copy a file in python?
. But actually, I want to copy a file to a folder/directory whereas most answers to that question mention copying one file to another file.
Use shutil.copy(filePath, folderPath) instead of shutil.copyfile(). This will allow you to specify a folder as the destination and copies the file including permissions.
shutil.copy(src, dst, *, follow_symlinks=True):
Copies the file src to the file or directory dst. src and dst should be strings. If dst specifies a directory, the file will be copied into dst using the base filename from src. Returns the path to the newly created file.
...
copy() copies the file data and the file’s permission mode (see os.chmod()). Other metadata, like the file’s creation and modification times, is not preserved. To preserve all file metadata from the original, use copy2() instead.
https://docs.python.org/3/library/shutil.html#shutil.copy
See the difference in copying also documented in shutil.copyfile() itself:
shutil.copyfile(src, dst, *, follow_symlinks=True):
Copy the contents (no metadata) of the file named src to a file named dst and return dst. src and dst are path names given as strings. dst must be the complete target file name; look at shutil.copy() for a copy that accepts a target directory path. If src and dst specify the same file, SameFileError is raised.
https://docs.python.org/3/library/shutil.html#shutil.copyfile
folderpath must be a file, not a directory. The error says it all. Do something like:
shutil.copyfile(filePath, folderPath+'/file_copy.extension')
Change your code as below:
folderPath = os.path.join('folder_name', os.path.basename(filePath))
shutil.copyfile(filePath, folderPath)
I think I can do this using python, but I'm not sure.
I have a bunch of .xlsx files in a folder (call it User/Data/Input) and I need to save all of them into a different folder (call it User/Data/Output).
Instead of having to open each excel file from the Input folder, and then save it to the Output folder manually, I'd like a program that can do that for me. I do not need to change the workbook names when this occurs, I just need them to be saved in the output folder.
Thanks!
shutil.copy(src, dst)
From the doc
"Copy the file src to the file or directory dst. If dst is a directory, a file with the same basename as src is created (or overwritten) in the directory specified. Permission bits are copied. src and dst are path names given as strings."
I am very new to Python. I want to copy set of files from one folder to another based on the name and not based on data types. So I have a source folder with files like Hello.txt, Hello.dat, Hello.pdf, World.txt, World.dat, Word.pdf. Now I just want to copy files beginning with "Hello" into another folder. I tried many ways but all seems to be based on data type.
import os
import shutil
files = os.listdir("Path")
for file in files:
if file.startswith("Hello"):
shutil.copy("Full path to file", "Full path to dest folder")