Python: 用于创建和写入两个输出文件的函数

Python: functions for creating and writing two output files

我正在尝试编写一个程序来读取一个 csv 文件,然后根据输入文件创建两个不同的输出文件。

file = open("file.csv","r") 

def createFile(data_set):
    output0 = open("Output" + data_set + ".txt","w")
    print >> output0, 'h1,h2,h3,h4'
    return output0

def runCalculations(data_set, output):
    for row in file:        
    # equations and stuff

        if data_set == 1:
            print >> output, row[1]+','+row[2]+','+row[3]+','+x
        if data_set == 2: 
            print >> output, row[4]+','+row[5]+','+row[6]+','+y

    output.close()

output1 = createFile(1)
runCalculations(1, output1)

output2 = createFile(2)
runCalculations(2, output2)

file.close()

Output1 完美,格式正确,一切都应该如此。对于 Output2,文件已创建,列的 headers 可见(因此 'createFile' 工作正常),但 'runCalculations' 函数从未运行,包括方程式(我检查过在这里和那里放置一些打印功能)

没有错误消息,我已经尝试更改每个函数和参数中输出文件的变量名(之前都是 'output')。我还尝试在 'runCalculations' 方法之外单独关闭每个文件(output1 和 output2)。我错过了什么阻止 'runCalculations' 函数被第二次调用?

抱歉,如果解决方案非常明显,我已经为此工作了一段时间,所以新鲜的眼光会很有帮助。非常感谢您的宝贵时间!

当第一次执行 runCalculations 时,您将遍历 file 对象,循环结束后您将到达文件末尾。 这就是为什么你第二次运行runCalculations不计算的原因。您必须回到文件的开头。

为此,在 runCalculations 函数末尾添加 file.seek(0)

函数runCalculations耗尽数据文件。那就是问题所在。打开文件并在 runCalculations 关闭文件将是测试版。最好在 runCalculations 中创建输出文件,见下文

def createFile(data_set):
    output0 = open("Output" + data_set + ".txt","w")
    print >> output0, 'h1,h2,h3,h4'
    return output0

def runCalculations(data_set, output):
    file = open("file.csv","r")
    output = createFile(data_set)
    for row in file:        
    # equations and stuff

        if data_set == 1:
            print >> output, row[1]+','+row[2]+','+row[3]+','+x
        if data_set == 2: 
            print >> output, row[4]+','+row[5]+','+row[6]+','+y

    output.close()
    file.close()

runCalculations(1)

runCalculations(2)