简体   繁体   English

将每一行写入具有csv扩展名的文件

[英]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. 当我将文件扩展名更改为.csv时,它在单元格外部输出,混乱。

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?) 然后它会像这样打印:( 但是如何将其映射到excel单元格?)

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 我该如何将它们打印到一个excel文件中,作为一行打印到单元格中

Read the docs . 阅读文档 Python is famous for having great documentation with thorough examples. Python以提供详尽的示例文档而著称。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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