如何将打印函数追加并保存到excel或csv?

2024-10-02 14:30:56 发布

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

如何将打印函数追加并保存到excel或csv

代码:


firstpts= ['20']
for pfts in firstpts:
    try:
          (Operation)
        print('test11 : PASSED')

    except:
        (Operation)
        print('test11 : FAILED')


secondpts= ['120']
for sfts in secondpts:
    try:
         (Operation)
        print('test22 : PASSED')

    except:
        (Operation)
        print('test22 : FAILED')

如果我运行这个代码,我会在输出中得到这个

test11 : PASSED
test22 : FAILED

如何将所有try的输出重定向到csv


Tags: csv代码inforexceloperationprinttry
2条回答

创建一个csv文件,并在其中写入信息

firstpts= ['20']
for pfts in firstpts:
    if int(pfts) < 100:
        print('test11 : PASSED')
        result_test11 = 'test11 : PASSED'
    else:
        print('test11 : FAILED')
        result_test11 = 'test11 : FAILED'

secondpts= ['120']
for sfts in secondpts:
    if int(sfts) < 100:
        print('test22 : PASSED')
        result_test22 = 'test22 : PASSED'
    else:
        print('test22 : FAILED')
        result_test22 = 'test22 : FAILED'

f = open("file.csv","w+")
f.write("{}\n{}".format(result_test11, result_test22))
f.close()

首先,你对try-catch的基本用法是错误的,因为如果elsing

不管怎样,抛开这一点不谈,您需要将所有记录的语句收集到一个字符串中,然后将该字符串写入一个“.csv”文件

就像this:- 你知道吗

# @author Vivek
# @version 1.0
# @since 24-08-2019

data = ""
firstpts = [20]
for pfts in firstpts:
    try:
        if pfts < 100:
            print('test11 : PASSED')
            data = 'test11 : PASSED\n'

    except:
        if pfts > 100:
            print('test11 : FAILED')
            data += 'test11 : PASSED\n'

secondpts = [120]
for sfts in secondpts:
    try:
        if sfts < 100:
            print('test22 : PASSED')
            data += 'test11 : PASSED\n'

    except:

        if sfts > 100:
            print('test22 : FAILED')
            data += 'test22 : FAILED'

file = open('test.csv', 'w')
file.write(data)
file.close()

相关问题 更多 >