Python Forum

Full Version: Shuntil.copyfile help
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So when I run this, I get "TypeError: bad operand type for unary +: 'str'"

import os
import shutil

src = os.path.expanduser('~/Downloads')
print(src)
os.getcwd()
dst = os.getcwd
print(dst)

for root, dirs, files in os.walk(src):
    for file in files:
        if file.endswith(('.txt', '.md')):
        print(os.path.join(root,file))
        shutil.copyfile(dst, +file)
Why do you have the unary plus operator there? Why do you intend for it to do?
I'm trying to copy the .txt and .md files from src to dst
Why the plus though, specifically? Have you tried just omitting it?
yeah I get this error:
Traceback (most recent call last):
File "CopySlides.py", line 14, in <module>
shutil.copyfile(dst, file)
File "C:\Users\mcesm\AppData\Local\Programs\Python\Python38\lib\shutil.py", line 238, in copyfile
if _samefile(src, dst):
File "C:\Users\mcesm\AppData\Local\Programs\Python\Python38\lib\shutil.py", line 217, in _samefile
return os.path.samefile(src, dst)
File "C:\Users\mcesm\AppData\Local\Programs\Python\Python38\lib\genericpath.py", line 100, in samefile
s1 = os.stat(f1)
TypeError: stat: path should be string, bytes, os.PathLike or integer, not builtin_function_or_method

when i run the code with #shutil.copyfile(dst, file) (out of the code) it prints everything with no errors
join path together for both scr and dst,then get absolute path for both and copying should work fine.

Example tested.
import os
import shutil
from os.path import join

src = r'E:\div_code\pan'
dst = r'E:\div_code\new_folder'
for root, dirs, files in os.walk(src):
    for file in files:
        if file.endswith(('.txt', '.md')):
            shutil.copyfile(join(src, file), join(dst, file))
Thank you, it worked! Is there a way of copying ALL the files, even duplicate names?