首页 > 解决方案 > I am opening 3 files in Python. The two read files are fine "with open" but the write file only works using "open"

问题描述

Update: When I tried to get a minimal program today, I realized there is an os.system('cmd /k') line that is probably causing the issue. I am not sure why but it must be autoclosing the file when I use the with open. @wjandrea thank you for suggesting that.

I am pretty new to python so I might be missing something basic although I have run tutorials and searched on "with" and "open". Nothing should be changed in the two code fragments below (the rest of the code is mostly comments where I sketched out what I want to do eventually and variable declaration and initialization) except the lines:

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

and the indenting (I went back and tried making sure the empty lines indenting matched the programmed lines although I wasn't sure that was an issue. It didn't help.)

The "with open" works for the read files but I can't get it to work for the write file.


Code using with open for sigMatch: Yields empty file.

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()

Code using open for sigMatch: Yields file with written output.

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()

标签: pythonwith-statement

解决方案


推荐阅读