简体   繁体   中英

How to solve "TypeError: list indices must be integers or slices, not str"

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.

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.

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)

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