Python mkdir问题,文件存在

2024-10-02 02:29:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在每个文件夹中创建目录和文件,使用输入文件中的数据。你知道吗

它适用于第一个,但随后会给我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()

Tags: 文件readdataindexlenifosfind
1条回答
网友
1楼 · 发布于 2024-10-02 02:29:44

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)。你知道吗

相关问题 更多 >

    热门问题