Python声明文件对象但不打开文件

问题描述

我正在编写一个需要写入文件的 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.

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...