问题描述
我正在编写一个需要写入文件的 Python 程序。我需要一个 if 条件来确定我是否需要继续写入同一个文件或打开一个新文件。如何声明文件以便我可以使用 if 和 else 访问它?现在我正在循环之前制作一个测试文件,以便我可以访问该变量。如何避免打开 TEST.txt 文件,同时仍然有一个我可以操作的变量 f?
f = open(outputFolder + "TEST.txt",'w') # how to avoid opening TEST.txt here
while row:
#print(str(row[0]) + '|' + str(row[4]))
currentFileName = getFileName(str(row[0]))
# If coming up on new date open new file
if currentFileName != fileName:
f.close()
fileName = currentFileName
print("Processing: " + fileName)
f = open(outputFolder + fileName,'w')
f.write(getLine(row))
# else write to current file
else:
f.write(getLine(row))
row = cursor.fetchone()
解决方法
您在编写程序之前没有弄清楚您的逻辑。您用文字描述的内容与您写的内容不符。从单词开始,绘制流程图,然后然后编写代码。
在您发布的程序中,您尝试多次打开 currentFile
,您没有初始化或更改 row
,并且不清楚您打算让程序做什么。
if [condition]:
filename = currentFileName
else:
filename = "TEST.txt"
f = open(filename)
for ... # whatever you're trying to do with your input and output,# look up the proper method in a file-handling tutorial.