Reputation: 79
The script reads a file syslog.log
that has error messages, parses it, builds a dictionary, and then writes the dictionary to user_statistics.csv
file.
I would like to write the integers from key:list
without the brackets, quotes or white space.
#!/usr/bin/python3
import csv
per_user = {'noel': [2, 2], 'mcintosh': [2, 1], 'enim.non': [1, 1], 'oren': [0, 2], 'bpacheco': [0, 1], 'mdouglas': [0, 1], 'ac': [1, 0], 'blossom': [0, 1]}
with open('user_statistics.csv', 'w') as csvfile1:
y = csv.writer(csvfile1)
y.writerow(['Username', 'INFO', 'ERROR'])
y.writerows(per_user.items())
output received in user_statistics.csv
Username,INFO,ERROR
ac,"[1, 0]"
blossom,"[0, 1]"
bpacheco,"[0, 1]"
enim.non,"[1, 1]"
mcintosh,"[2, 1]"
mdouglas,"[0, 1]"
oren,"[0, 2]"
Desired output is
Username,INFO,ERROR
ac,1,0
blossom,0,
bpacheco,0,1
enim.non,1,1
mcintosh,2,1
mdouglas,0,1
oren,0,2
Upvotes: 2
Views: 219
Reputation: 1377
solution with pandas (instead of second with
statement).
import pandas as pd
keys = per_user.keys()
values = per_user.values()
df_keys = pd.DataFrame(keys, columns=['Username'])
df_values = pd.DataFrame(values, columns=['INFO', 'ERROR'])
data = df_keys.join(df_values)
data.to_csv("user_statistics.csv", index=False)
Outputs:
Username,INFO,ERROR
ac,1,0
blossom,0,1
bpacheco,0,1
enim.non,1,1
mcintosh,2,1
mdouglas,0,1
oren,0,2
Upvotes: 0
Reputation: 96098
You just need to do something like:
import csv
per_user = {'noel': [2, 2], 'mcintosh': [2, 1], 'enim.non': [1, 1], 'oren': [0, 2], 'bpacheco': [0, 1], 'mdouglas': [0, 1], 'ac': [1, 0], 'blossom': [0, 1]}
with open('user_statistics.csv', 'w') as csvfile1:
writer = csv.writer(csvfile1)
writer.writerow(['Username', 'INFO', 'ERROR'])
for name, (info, error) in per_user.items():
writer.writerow([name, info, error])
Upvotes: 3