skip to Main Content

I have 2 files to copy from a folder to another folder and these are my codes:

import shutil

src = '/Users/cadellteng/Desktop/Program Booklet/'
dst = '/Users/cadellteng/Desktop/Python/'
file = ['AI+Product+Manager+Nanodegree+Program+Syllabus.pdf','Artificial+Intelligence+with+Python+Nanodegree+Syllabus+9-5.pdf']

for i in file:
    shutil.copyfile(src+file[i], dst+file[i])

When I tried to run the code I got the following error message:

/Users/cadellteng/venv/bin/python /Users/cadellteng/PycharmProjects/someProject/movingFiles.py
Traceback (most recent call last):
  File "/Users/cadellteng/PycharmProjects/someProject/movingFiles.py", line 8, in <module>
    shutil.copyfile(src+file[i], dst+file[i])
TypeError: list indices must be integers or slices, not str

Process finished with exit code 1

I tried to find some solution on stackoverflow and one thread suggest to do this:

for i in range(file):
    shutil.copyfile(src+file[i], dst+file[i])

and then I got the following error message:

/Users/cadellteng/venv/bin/python /Users/cadellteng/PycharmProjects/someProject/movingFiles.py
Traceback (most recent call last):
  File "/Users/cadellteng/PycharmProjects/someProject/movingFiles.py", line 7, in <module>
    for i in range(file):
TypeError: 'list' object cannot be interpreted as an integer

Process finished with exit code 1

So now I am thoroughly confused. If “i” can’t be a string and it can’t be an integer, what should it be?
I am using PyCharm CE and very new to Python.

2

Answers


  1. Try the code below, and read for Statement in python

    import shutil
    
    src = '/Users/cadellteng/Desktop/Program Booklet/'
    dst = '/Users/cadellteng/Desktop/Python/'
    file = ['AI+Product+Manager+Nanodegree+Program+Syllabus.pdf','Artificial+Intelligence+with+Python+Nanodegree+Syllabus+9-5.pdf']
    
    for i in file:
        shutil.copyfile(src + i, dst + i)
    
    Login or Signup to reply.
  2. Just use the below code since i doesn’t need an extra indexing file[...], because it is not an index:

    for i in file:
        shutil.copyfile(src + i, dst + i)
    

    If you want to use range, use it this way with len:

    for i in range(len(file)):
        shutil.copyfile(src+file[i], dst+file[i])
    

    But of course the first solution is preferred.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search