[英]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:我有 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])
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:我试图在 stackoverflow 上找到一些解决方案,一个线程建议这样做:
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”不能是字符串,也不能是整数,它应该是什么? I am using PyCharm CE and very new to Python.
我正在使用 PyCharm CE 并且对 Python 非常陌生。
Just use the below code since i
doesn't need an extra indexing file[...]
, because it is not an index:只需使用以下代码,因为
i
不需要额外的索引file[...]
,因为它不是索引:
for i in file:
shutil.copyfile(src + i, dst + i)
If you want to use range
, use it this way with len
:如果要使用
range
,请以这种方式与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试试下面的代码,并在 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.