【问题标题】:Same filename different path in subtree子树中相同的文件名不同的路径
【发布时间】:2013-08-21 10:47:22
【问题描述】:

我需要创建指向目录 (dir1) 中文件的符号链接。每个文件必须有一个符号链接,如果有一个具有相同文件名但在子文件夹中的文件,我需要创建一个带后缀的符号链接。这是一个例子: dir1 包含文件 exe1、sh1、bash。目录文件也包含文件bash,文件file1,file2 file3。

exe1 → dir1/exe1
sh1 → dir1/sh1
bash → dir1/bash
bash1 → dir1/paper/bash
file1 → dir1/paper/file1
file2 → dir1/paper/file2
file3 → dir1/paper/file3

代码是python。谁能帮帮我?

【问题讨论】:

  • 到目前为止你尝试了什么。任何一段代码或你写过/尝试过的东西??
  • 所以我知道你想要一些免费代码...
  • 我不想要免费代码,我只是不知道如何检查文件是否在子文件夹中出现更多次,然后为我需要创建的符号链接添加后缀。
  • 如果dir1/paper/ 包含exe1,你想要什么结果?它exe11?
  • @MichaelKazarian 是的,完全正确!

标签: python file directory


【解决方案1】:

为什么不在创建新链接之前检查链接是否已经存在,并增加后缀直到获得新链接名称?

【讨论】:

    【解决方案2】:
    import os, sys
    
    def maker(inputdir, outputdir, suffix=""):
        if not (chechdir(inputdir) and chechdir(outputdir)): sys.exit(0)
        for pos in os.listdir(inputdir):
            name =  os.path.abspath(inputdir+"/"+pos)
            if os.path.isdir(name):
                maker(name, outputdir, suffix+"1")
            else:
                simlnkname = os.path.abspath(outputdir+"/"+pos)
                if os.path.exists(simlnkname):
                    simlnkname += suffix
                os.symlink(name, simlnkname)
    
    
    def chechdir(directory):
        if not (os.path.exists(directory) and os.path.isdir(directory)):
            print "Error directory ", directory
            return False
        return True
    
    if __name__ == "__main__":
        inp = "dir1"
        outp = "dir2"
        maker(inp, outp)
    

    测试一下:

    $ tree
    .
    ├── dir1
    │   ├── bash
    │   ├── exe1
    │   ├── paper
    │   │   ├── bash
    │   │   ├── file1
    │   │   ├── file2
    │   │   └── file3
    │   └── sh1
    ├── dir2
    └── test.py
    
    3 directories, 8 files
    $ python test.py 
    $ tree
    .
    ├── dir1
    │   ├── bash
    │   ├── exe1
    │   ├── paper
    │   │   ├── bash
    │   │   ├── file1
    │   │   ├── file2
    │   │   └── file3
    │   └── sh1
    ├── dir2
    │   ├── bash -> /home/miha/exampldir/dir1/bash
    │   ├── bash1 -> /home/miha/exampldir/dir1/paper/bash
    │   ├── exe1 -> /home/miha/exampldir/dir1/exe1
    │   ├── file1 -> /home/miha/exampldir/dir1/paper/file1
    │   ├── file2 -> /home/miha/exampldir/dir1/paper/file2
    │   ├── file3 -> /home/miha/exampldir/dir1/paper/file3
    │   └── sh1 -> /home/miha/exampldir/dir1/sh1
    └── test.py
    
    3 directories, 15 files
    

    It 概念,在 linux 中什么工作。所以有理由在运行之前清理outpdir2 换句话说)。

    【讨论】:

      猜你喜欢
      • 2013-12-30
      • 2013-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-14
      • 2021-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多