如何解决“ TypeError:列表索引必须是整数或切片,而不是str”

问题描述 投票:2回答:2

我有2个文件要从一个文件夹复制到另一个文件夹,这些是我的代码:

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])

[当我尝试运行代码时,出现以下错误消息:

/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

我试图在stackoverflow上找到一些解决方案,并且有一个线程建议这样做:

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

然后我收到以下错误消息:

/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

所以现在我很困惑。如果“ i”不能是字符串,也不能是整数,那应该是什么?我正在使用PyCharm CE,并且是Python的新手。

python shutil
2个回答
3
投票

只需使用以下代码,因为i不需要额外的索引file[...],因为它不是索引:

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

如果要使用range,请与len一起使用:

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

但是当然首选第一个解决方案。


2
投票

尝试下面的代码,然后阅读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)
© www.soinside.com 2019 - 2024. All rights reserved.