2013-08-21 46 views
-1

我需要制作符号链接到目录(dir1)中的文件。每个文件必须有一个symbolik链接,如果有一个文件具有相同的文件名,但在子文件夹中,我需要使用后缀进行符号链接。这里是一个例子: 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。任何人都可以帮助我?

+0

你到目前为止尝试过什么。任何代码或你已经写/尝试过的东西? –

+0

所以我看到你想要一些免费的代码... – Sheena

+0

我不想要免费的代码,我只是不知道如何检查文件是否存在多次在子文件夹中,然后添加后缀到符号链接我需要创建。 –

回答

0

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

0
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 

它的概念,哪些工作在Linux操作系统。因此,在运行之前清理outpdir2其他词)是有理由的。

相关问题