我正在用Python打开3个文件。两个读取文件在“打开”状态下都可以,但是写入文件只能在“打开”状态下工作

我对python很陌生,因此尽管我已经运行了教程并在“ with”和“ open”上进行了搜索,但我可能仍缺少一些基本知识。除以下两行外,下面的两个代码片段(其余的代码大部分是我在其中勾画出最终要执行的操作以及变量声明和初始化的注释)应保持不变:

with open(fileDirectory+sigMatchFile, "w") as sigMatch: which doesn't give output in the file

sigMatch = open(fileDirectory+sigMatchFile, "w") which gives output in the file

和缩进(我回过头去尝试确保缩进的空行与编程的行匹配,尽管我不确定那是一个问题。它没有帮助。)

“打开”功能适用于读取文件,但我无法使其适用于写入文件。

与open一起使用的sigMatch的代码:产生空文件。

with open(fileDirectory+sigMatchFile, "w") as sigMatch:
    sigMatch.write("1 - Testing if opened\n")

    with open(fileDirectory+currentFastaFile, "r") as fasta:
        fl = fasta.readline().split("|")
        currentGene = fl[1]
        fasta.close()
    sigMatch.write("2 - Testing if still open\n")

    with open(fileDirectory+blastpFile, "r")as blastp:
        blpl = blastp.readlines()
        for x in blpl:
            if "significant alignments:" in x:
                print ("significant alignments: " + x)
                sigMatch.write("3 - Testing if still open\n")
                sigMatch.write("significant alignments: " + x +"\n")

        blastp.close()
    sigMatch.close()

使用open进行sigMatch的代码:产生具有书面输出的文件。

sigMatch = open(fileDirectory+sigMatchFile, "w")
sigMatch.write("1 - Testing if opened\n")

with open(fileDirectory+currentFastaFile, "r") as fasta:
    fl = fasta.readline().split("|")
    currentGene = fl[1]
    fasta.close()
sigMatch.write("2 - Testing if still open\n")

with open(fileDirectory+blastpFile, "r")as blastp:
    blpl = blastp.readlines()
    for x in blpl:
        if "significant alignments:" in x:
            print ("significant alignments: " + x)
            sigMatch.write("3 - Testing if still open\n")
            sigMatch.write("significant alignments: " + x +"\n")

    blastp.close()
sigMatch.close()
评论