Python mkdir问题,文件存在错误

时间:2017-07-03 23:11:42

标签: python while-loop 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()

1 个答案:

答案 0 :(得分:3)

std::ostream不应该以这种方式使用 - 而是使用其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