简体   繁体   中英

Copy Files by getting name from text file. - Python

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'

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM