python - 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()
解决方案
推荐阅读
- google-apps-script - 替换 Sheet 中的 Reference DOCS 文件名。文件
- python - 错误:gcloud 崩溃(OSError):[Errno 45] 不支持操作
- java - 有什么方法可以隐藏当前位置和 jdk 位置吗?
- python - 对于异常程序,如果您没有获得所需的输出,如何在使用 Python 最多 3 次尝试后退出程序?
- logging - erlang logger 不显示进度报告
- reactjs - 子组件的渲染会触发不需要的卸载
- flutter - 如何在 Flutter 中使用 Rest API 创建推送通知?
- java - rlike 正则表达式不处理特殊字符
- json - 如何加快 ruby 中的 json API 响应?
- asp.net-core - EF Core:从集合中删除子实体