标签的不一致使用

3
我正在尝试在Windows 7中查找/Users/目录中的所有.mp3和.mp4文件。以下是我的代码。有什么想法吗?
import os
newpath = r'C:\Users\Media' 
    if not os.path.exists(newpath):
      os.makedirs(newpath)
for root, dirs, files in os.walk("/Users"):
     for file in files:
         if file.endswith(".mp3"):
             print(os.path.join(root, file))
             os.rename(os.path.join(root, file), newpath)
for root, dirs, files in os.walk("/Users"):
    for file in files:
         if file.endswith(".mp4"):
             print(os.path.join(root, file))
             os.rename(os.path.join(root, file), newpath)  

检查空格并可以将两个for循环合并为一个(添加elif)。 - Avinash Raj
3
提示:if file.endswith(".mp3") or file.endswith(".mp4")。 如果文件以".mp3"或者".mp4"结尾,就执行下面的操作。 - Remi Guan
另一个提示:如果您有Python> = 3.5,则可以使用类似于glob.iglob(r'C:\ Users \ ** \ * .mp3',recursive = True)的东西([文档](https://docs.python.org/3/library/glob.html))。 - Cristian Ciupitu
1个回答

1
您的代码基本上是正确的,但唯一需要注意的是,在上面给出的代码中,第一个if语句前有一个制表符,但在任何情况下都不需要。这就是为什么会出现错误的原因。请删除该制表符或缩进以解决问题。更正后的代码如下所示:
import os
newpath = r'C:\Users\Media' 
if not os.path.exists(newpath):
      os.makedirs(newpath)
for root, dirs, files in os.walk("/Users"):
     for file in files:
         if file.endswith(".mp3"):
             print(os.path.join(root, file))
             os.rename(os.path.join(root, file), newpath)
for root, dirs, files in os.walk("/Users"):
    for file in files:
         if file.endswith(".mp4"):
             print(os.path.join(root, file))
             os.rename(os.path.join(root, file), newpath)  

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接