2017-07-03 727 views
0

我試圖使用來自輸入文件的數據在每個文件夾中創建目錄和文件。Python mkdir問題,文件存在錯誤

它適用於第一個,但隨後給我FileExistsError

我在這個一直盯着幾個小時,現在,只是似乎無法得到它,任何幫助,將不勝感激。

文件數據看起來像這樣

>unique id 
string of unknown length 

,我已經試過代碼是這樣

import os 


# find a character 

CharLocArray = [] 

NewLineArray = [] 

with open('/home/tjbutler/software/I-TASSER5.0/seqdata/Egg_protein/seq.fasta', 'r') as myfile: 

    data = myfile.read() 
    GreaterThan = '>' 
    NewLine = '\n' 

    # code to read char into var 
    # myfile.read().index('>') 
    index = 0 
    while index < len(data): 
     index = data.find('>', index) 
     CharLocArray.append(index) 
     if index == -1: 
      break 

     index += 2 

    index2 = 0 
    while index2 < len(data): 
     index2 = data.find('\n', index2) 
     NewLineArray.append(index2) 
     if index2 == -1: 
      break 

     index2 += 2 

    i = 0 
    print(len(CharLocArray)) 

    while i < len(CharLocArray): 
     print(i) 
     CurStr = data[CharLocArray[i]:] 
     CurFolder = CurStr[CharLocArray[i]:NewLineArray[i]] 
     print(CurFolder) 
     CurData = CurStr[CharLocArray[i]:CharLocArray[i + 1]] 
     print(CurData) 
     newpath = r'/home/tjbutler/software/I-TASSER5.0/seqdata/Egg_protein/' 
     DirLocation = newpath + CurFolder 
     print(DirLocation) 
     FileLocation = DirLocation + '/seq.fasta' 
     print(FileLocation) 
     i = i + 1 
     print(i) 
     if not os.makedirs(DirLocation): 
      os.makedirs(DirLocation) 
      file = open(FileLocation, 'w+') 
      file.write(CurData) 
      file.close() 

回答

3

os.makedirs()不應該用這種方式 - 使用其exist_ok說法相反:

os.makedirs(DirLocation, exist_ok=True) # instead of the condition! 
    with open(FileLocation, 'w+') as f: 
     f.write(CurData) 

另外,不要手動創建自己的路徑(即FileLocation = DirLocation + '/seq.fasta'),請使用os.path設施,例如:FileLocation = os.path.join(DirLocation, seq.fasta)