我需要一个脚本,它可以递归地遍历c:somedir并将文件移动到c:someotherdirx -其中x是文件的起始字母。
有人能帮忙吗?
以这个结尾:
import os
from shutil import copy2
import uuid
import random
SOURCE = ".\pictures\"
DEST = ".\pictures_ordered\"
for path, dirs, files in os.walk(SOURCE):
for f in files:
print(f)
starting_letter = f[0].upper()
source_path = os.path.join(path, f)
dest_path = os.path.join(DEST, starting_letter)
if not os.path.isdir(dest_path):
os.makedirs(dest_path)
dest_fullfile = os.path.join(dest_path, f)
if os.path.exists(dest_fullfile):
periodIndex = source_path.rfind(".")
renamed_soruce_path = source_path[:periodIndex] + "_" + str(random.randint(100000, 999999)) + source_path[periodIndex:]
os.rename(source_path, renamed_soruce_path)
copy2(renamed_soruce_path, dest_path)
os.remove(renamed_soruce_path)
else:
copy2(source_path, dest_path)
os.remove(source_path)`
下面是一个简单的脚本,可以满足您的需求。它不会告诉你它在做什么,如果有两个同名的文件,它只会覆盖旧的文件。
import os
from shutil import copy2
SOURCE = "c:\source\"
DEST = "c:\dest\"
# Iterate recursively through all files and folders under the source directory
for path, dirs, files in os.walk(SOURCE):
# For each directory iterate over the files
for f in files:
# Grab the first letter of the filename
starting_letter = f[0].upper()
# Construct the full path of the current source file
source_path = os.path.join(path, f)
# Construct the destination path using the first letter of the
# filename as the folder
dest_path = os.path.join(DEST, starting_letter)
# Create the destination folder if it doesn't exist
if not os.path.isdir(dest_path):
os.makedirs(dest_path)
# Copy the file to the destination path + starting_letter
copy2(source_path, dest_path)
我怀疑这将在PowerShell中工作。
gci -path c:somedir -filter * -recurse |
where { -not ($_.PSIsContainer) } |
foreach { move-item -path $_.FullName -destination $_.Substring(0, 1) }
ls c:somedir* -recurse | ? { -not ($_.PSIsContainer)} | mv -destination "C:someotherdir$($_.Name.substring(0,1))" }
…-whatif
: P
这是Python中的答案,注意警告消息,您可能希望以不同的方式处理覆盖。还要将它保存到根目录下的一个文件中,并在那里运行它,否则您必须将参数更改为os。以及路径是如何连接在一起的
import os
import sys
try:
letter = sys.argv[1]
except IndexError:
print 'Specify a starting letter'
sys.exit(1)
try:
os.makedirs(letter)
except OSError:
pass # already exists
for dirpath, dirnames, filenames in os.walk('.'):
for filename in filenames:
if filename.startswith(letter):
src = os.path.join(dirpath, filename)
dst = os.path.join(letter, filename)
if os.path.exists(dst):
print 'warning, existing', dst, 'being overwritten'
os.rename(src, dst)
当然,我会帮助:看看Python2中的os.path.walk,我相信这只是os。