0

I am trying to copy few files from one folder to another by reading names of files from a text file "input.txt". What did I do wrong? Thank you in advance.

import shutil
import os
f = open('input.txt','r')
src=r'C:\Users\abhishekcho\Desktop\Self\folder1'
dst=r'C:\Users\abhishekcho\Desktop\Self\folder2'

for i in range(4):
    file_name = f.readline()
    source = os.path.join(src,file_name)
    shutil.copy2(source,dst)

Output:

PS C:\Users\abhishekcho\Desktop\Self> &
C:/Users/abhishekcho/AppData/Local/Programs/Python/Python37-32/python.exe
c:/Users/abhishekcho/Desktop/Self/test.py Traceback (most recent call
last):   File "c:/Users/abhishekcho/Desktop/Self/test.py", line 10, in
<module>
    shutil.copy2(source,dst)   File "C:\Users\abhishekcho\AppData\Local\Programs\Python\Python37-32\lib\shutil.py",
line 263, in copy2
    copyfile(src, dst, follow_symlinks=follow_symlinks)   File "C:\Users\abhishekcho\AppData\Local\Programs\Python\Python37-32\lib\shutil.py",
line 120, in copyfile
    with open(src, 'rb') as fsrc: OSError: [Errno 22] Invalid argument:
'C:\\Users\\abhishekcho\\Desktop\\Self\\folder1\\text1.txt\n'
2
  • 1
    No, it's just because readline leaves a trailing newline. Commented Nov 22, 2020 at 11:54
  • Yes, It worked by adding rstrip() after readline as suggested by BenB. Commented Nov 22, 2020 at 12:31

1 Answer 1

2

Seems as if the trailing newline character \n was included in your path and caused the error. You can remove it with rstrip()

import shutil
import os
f = open('input.txt','r')
src=r'C:\Users\abhishekcho\Desktop\Self\folder1'
dst=r'C:\Users\abhishekcho\Desktop\Self\folder2'

for i in range(4):
    file_name = f.readline().rstrip()
    source = os.path.join(src,file_name)
    shutil.copy2(source,dst)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.