Search code examples
pythonpython-3.xcsvtry-catchsys

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


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

code :


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')

If i run this code i"ll get this in output

test11 : PASSED
test22 : FAILED

How to redirect that outputs of all try-except cases to a csv


Solution

  • First things first, your fundamental use of try-catch is wrong as is, for if-elsing.

    Anyways, that aside, you would need to collect all of your logged statements in a string and then write that string to a '.csv' file.

    Like 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()