简体   繁体   中英

Write each line to a file with a csv extension

I am currently writing to a log file via the below classic way; to write my values that are populated and handled elsewhere in my application.

When I change the file extension to .csv, it outputs outside of cells, messy.

old_stdout = sys.stdout
log_file = open("./logs/metrics.log","w") # I want this to be excel instead, when I change to csv it outputs outside of cells, messy
sys.stdout = log_file

# this to be one excel row (or record)

print(f"Total Records Found #{total_records} records") # this to be excel cell
print(f"Records Processing #{num_valid_records} records") # this to be excel cell
print(f"Records Deemed Invalid (skipped) #{num_invalid_records} records") # this to be excel cell
success_rate = num_valid_records / total_records * 100
print("Sucess Rate:") # this to be excel cell
print(success_rate) # this to be excel cell

then it prints like this: (but how can I map this to excel cells?)

Total Records Found #351 records
Records Processing #350 records
Records Deemed Invalid (skipped) #1 records
Sucess Rate:
99.71509971509973

I am wondering; how I can instead print these into an excel file, into cells as one row

Read the docs . Python is famous for having great documentation with thorough examples.

from csv import DictWriter

with open("./logs/metrics.csv", "w", newline="") as f:
    csv_writer = DictWriter(f, ['total', 'processed', 'skipped', 'success_rate'])
    csv_writer.writeheader()

    success_rate = num_valid_records / total_records * 100
    csv_writer.writerow(dict(total=total_records,
                             processed=num_valid_records,
                             skipped=num_invalid_records,
                             success_rate=num_valid_records / total_records * 100))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM