如何将打印功能附加并保存到 excel 或 csv?

How to append and save a print function to excel or csv?

如何将打印函数追加并保存到 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-except 案例的输出重定向到 csv

创建一个文件 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()

首先,对于 if-elsing,您对 try-catch 的基本使用是错误的。

无论如何,除此之外,您需要将所有记录的语句收集到一个字符串中,然后将该字符串写入“.csv”文件。

像这样:-

# @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()