Python3 : Files organizing

标签 python file python-3.x

我在 Unix 系统上得到了这个文件路径:

Folder1/Folder2/text.txt

Folder1 仅包含Folder2,Folder2 包含该文件。所以文件test.txt的路径可以更短->Folder1/text.txt,我需要一些通用的解决方案:

if(folder contains only one subfolder)-> move files from subfolder to folder and del subfolder

最佳答案

从您的评论中我看到您想要移动Folder3 和Folder2 中的文件。这是一个程序,它将移动Folder1下所有文件夹中的所有文件,然后删除文件夹(但不删除Folder1)。首先,您必须更改目录Folder1。如果您要移动的任何文件已存在于Folder1 中,您将收到一条错误消息。不过你可以解决这个问题。我添加了一些打印语句,以便您可以看到它的工作原理。

import os, shutil
p = os.path._getfullpathname("Folder1")
print p
for root, dirs, files in os.walk(p, topdown=False):
    for file in files:
        k = os.path.join(root,file)
        print k
        shutil.move(k, p)
    for dir in dirs:
        k = os.path.join(root,dir)
        print k
        os.rmdir(k)

关于Python3 : Files organizing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36713096/

相关文章:

python - 在 Python 中创建大型随机内容文件

python - 从 python 3 中的用户输入中计算二元组?

python - 各种列表连接方法及其性能

django - 如何在 Django 开发中提供静态文件

c# - 锁定 AppendAllText 与 TextWriter

python - 在哪里可以找到使用诗歌安装的虚拟环境 |哪里可以找到诗装虚拟环境

python - 字符串操作,for循环不起作用

python - 如何使 pynput.keyboard 作为线程运行?

python - 帮助错误信息

c# - 如何在 .NET 中使用真实文件进行集成测试?