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

2024-09-30 16:35:48 发布

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

更新:当我今天试图获得一个最小的程序时,我意识到有一个os.system('cmd /k')行可能导致了这个问题。我不知道为什么,但当我使用with open时,它必须自动关闭文件@谢谢你的建议

我是python新手,所以我可能缺少一些基本的东西,尽管我已经运行了教程并搜索了“with”和“open”。在下面的两段代码中,除了以下几行之外,不应更改任何内容(代码的其余部分主要是注释,我在其中勾勒出了我最终要做的事情以及变量声明和初始化):

with open(fileDirectory+sigMatchFile, "w") as sigMatch:它不会在文件中给出输出

sigMatch = open(fileDirectory+sigMatchFile, "w")在文件中给出输出

还有缩进(我回去试着确保空行缩进与编程行匹配,虽然我不确定这是个问题,但没有帮助。)

“with open”适用于读取文件,但我无法使其适用于写入文件


使用with open for 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()

使用openforsigmatch:生成具有写入输出的文件的代码

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

Tags: 文件代码closeifaswithopentesting