Python code for writing csv files. Specify the directory and set the file name to date, time, etc. By adding date and time information to the file name, a file with a unique name can be created when it is executed, which is convenient for saving logs.
Output csv to the ʻoutput` directory of the same directory as csv_log.py.
csv_log.py
import datetime
import csv
#Get date and time
now = datetime.datetime.now()
#Specify the directory here
filename = './output/log_' + now.strftime('%Y%m%d_%H%M%S') + '.csv'
#File, first line(column)Creation
with open(filename, 'w') as f:
writer = csv.writer(f)
writer.writerow(['x','y','z'])
x,y,z = 0,0,0
while(1):
#Write some processing
x += 1
y += 2
z += 3
#Match filename to the name of the file you created
# writer.write list to csv with writerow
with open(filename, 'a', newline="") as f:
writer = csv.writer(f)
writer.writerow([x, y, z])
#Break when processing is finished
break
I think you can make a csv like this
x | y | z |
---|---|---|
1 | 2 | 3 |
4 | 5 | 6 |
: | : | : |
That's all for this time, but I often use pandas for data analysis, etc. I can easily output csv with pandas, so I will update it again. Thank you very much!
Recommended Posts