2013-08-21 51 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其他詞)是有理由的。

相關問題