linux 移动目录树到子目录中,python,将所有文件从目录树的第3,第4,第5级移动到第2级...

我知道我们有os.walk,但我无法弄清楚如何创建这个。

比方说,我有一个Ubuntu的Linux机器上的以下文件夹结构:

Maindir (as root called by script)

+- subdir-one

| +-subdir-two

| +-file

| +-another file

| +-subdir-three

| +-file3

| +-file4

| +-subdir-four

| +- file5

| +- file6

+- subdir-two

+- subdir-three

| +-sub-subdir-two

| +-file

| +-another file

| +-subdir-three

| +-file3

| +-file4

| +-subdir-four

| +-file5

| +-file6

+-subdir-four

+-subdir-two

+-file

+-another file

+-subdir-three

+-file3

+-file4

+-subdir-four

+-file5

+-file6我想将所有文件从子目录移动到级别2的子级,而不是根级别。

以subdir-one为例:将subdir-4中的所有文件移动到subdir-1(本例中为file5和file6),将所有文件从subdir-3移动到subdir-1(本例中为file3和file4)

Subdir-2没有其他的子目录,所以可以被脚本跳过。

Subdir-three:将所有文件从sub-subdir-2,subdir-3和subdir-4移动到subdir-3。

我认为你说对了。没有问题,如果文件被覆盖,如果他们有相同的名字,无论如何都是重复的,这是运行这个清理脚本的一个原因。

当所有文件从子目录移动时,这意味着子目录将是空的,所以我也想删除空的子目录。

14-1-2012更新:这是jcollado提供的更改代码,但仍无法使用。顺便说一句,我忘了提及,我也需要过滤一些目录名称。在目录树中找到这些目录名称时,需要排除它们的处理。

我稍微改变了代码:

import os, sys

def main():

try:

main_dir = sys.argv[1]

print main_dir

# Get a list of all subdirectories of main_dir

subdirs = filter(os.path.isdir,

[os.path.join(main_dir, path)

for path in os.listdir(main_dir)])

print subdirs

# For all subdirectories,

# collect all files and all subdirectories recursively

for subdir in subdirs:

files_to_move = []

subdirs_to_remove = []

for dirpath, dirnames, filenames in os.walk(subdir):

files_to_move.extend([os.path.join(dirpath, filename)

for filename in filenames])

subdirs_to_remove.extend([os.path.join(dirpath, dirname)

for dirname in dirnames])

# To move files, just rename them replacing the original directory

# with the target directory (subdir in this case)

print files_to_move

print subdirs_to_remove

for filename in files_to_move:

source = filename

destination = os.path.join(subdir, os.path.basename(filename))

print 'Destination ='+destination

if source != destination:

os.rename(source, destination)

else:

print 'Rename cancelled, source and destination were the same'

# Reverse subdirectories order to remove them

# starting from the lower level in the tree hierarchy

subdirs_to_remove.reverse()

# Remove subdirectories

for dirname in subdirs_to_remove:

#os.rmdir(dirname)

print dirname

except ValueError:

print 'Please supply the path name on the command line'

if __name__ == '__main__':

main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值