我试图在 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)
最佳答案
您的代码几乎是正确的,但唯一的问题是,在上面给出的代码中,第一个 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)
关于python - 选项卡的使用不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33602636/