将Python程序的输出写入.txt Fi

2024-04-25 22:00:10 发布

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

我写了一个程序,读取CSV文件并将内容作为insert语句输出。然后我编写了一个execute程序,应该获取CSV解析器程序的输出并将其写入一个.txt文件,但是它没有写入整个输出,而是只写入第一个语句。在

执行人代码如下:

import sys

with open('insert.txt', 'wb') as f:
    subprocess.check_call(["python", "CSVParserMultiple.py"], stdout=f)

以及解析器的代码:

^{pr2}$

我不完全确定将它们作为两个独立的程序是否有意义,但我一辈子都无法让它们在同一个程序中作为定义的函数运行。如何让执行程序输出解析器程序的所有行而不是一行?我怎样才能把它们组合成一个程序呢?


Tags: 文件csv代码import程序txt解析器内容
2条回答

你把事情弄得比实际情况更复杂。只需使用with嵌套您的打开语句。一个程序。然后打印到屏幕并写入文件。在

import csv, os

path = 'C:/Users/user/Desktop/test/'
for file in os.listdir(path):
    if file.endswith('.csv'):
        # print ('Parsing file: ' + os.path.basename(path + file))
        with open(path + file) as infile:
            with open(path+file+".txt",'w') as outfile:
                csvFile = csv.reader(infile)
                getHeader = next(csvFile)
                columnHeaders = map((lambda x: "'" + x + "'"), getHeader[:-1])
                insert = 'INSERT INTO testing (' + "'ID', 'VehicleID', " + ', '.join(columnHeaders) + ') VALUES '
                for row in csvFile:
                    values = map((lambda x: "'" + x.strip() + "'"), row[:-1])
                    print (insert + "(" + ", ".join(values) + ");")
                    outfile.write(insert + "(" + ", ".join(values) + ");" + "\n")

不确定这是否对您有效,但您可以使用>;/>;>运算符将stdout重新路由到文件。在

编辑:与>>的区别在于,在截短文件的同时,gt;>>追加到文件末尾

$python program.py >> output.txt

要组合这些程序,可以将executor程序定义为主函数,方法是将其定义为

^{pr2}$

然后可以使用

sys.stdout = open("file",'w')

类似问题:Redirect stdout to a file in Python?

相关问题 更多 >