Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Shuntil.copyfile help
#1
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)
Reply
#2
Why do you have the unary plus operator there? Why do you intend for it to do?
Reply
#3
I'm trying to copy the .txt and .md files from src to dst
Reply
#4
Why the plus though, specifically? Have you tried just omitting it?
Reply
#5
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
Reply
#6
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))
Reply
#7
Thank you, it worked! Is there a way of copying ALL the files, even duplicate names?
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020