2017-07-03 58 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)