美好的一天,
我正在写入csv文件,我需要将一列的信息分成两列 例如:
Call
Goku (1000)
要有这样的东西:
Name Landline
Goku 1000
所以我需要帮助删除数字周围的括号,只取其中的数字,同时将Call列标题重命名为Name,然后在写其他列之前创建一个名为Landline的新列,Name和Landline需要是第一个两列然后其他列跟随。
我有以下代码:
infile = "path to file"
outfile = "path to file"
def csv_wr():
# Opens output file for writing data into.
of = open(outfile, 'w')
# Reads the data from input file
with open(infile, 'r') as f:
data = csv.DictReader(f)
count = 0
# Writing data into output file.
for row in data:
# Converts the date column.
mydate = datetime.strptime(row['date'], '%d %b %Y %H:%M: %S').strftime('%Y-%m-%d %H:%M:%S')
x = ''.join(row['value'])
# Inserting '0' value to empty columns.
if len(x) < 1:
value = 0
else:
value = row['value']
# If statement inserting data with commas except for the last row into the output file.
if count > 0:
textline = ",\n('{0}','{1}','{2}','{3}','{4}','{5}','{6}')".format(row['call'], row['to'], mydate,
row['duration'], row['bill'],
value, row['status'])
else:
textline = "('{0}','{1}','{2}','{3}','{4}','{5}','{6}')".format(row['call'], row['to'], mydate,
row['duration'], row['bill'],
value, row['status'])
of.write(textline)
答案 0 :(得分:0)
最好使用csv.DictWriter()
来创建CSV文件。可以使用正则表达式拆分call
字段以获取name
和landline
部分。然后可以将其添加到字典中并使用.writerow()
调用来编写:
from collections import defaultdict
from datetime import datetime
import csv
import re
in_file = 'input.csv'
out_file = 'output.csv'
fieldnames = ['date', 'name', 'landline', 'to', 'duration', 'bill', 'status']
with open(in_file, 'r', newline='') as f_input, open(out_file, 'w', newline='') as f_output:
csv_input = csv.DictReader(f_input)
csv_output = csv.DictWriter(f_output, fieldnames=fieldnames, extrasaction='ignore')
csv_output.writeheader()
for row in csv_input:
name, landline = re.match(r'(.*?) \((.*?)\)', row['call']).groups()
row['name'] = name
row['landline'] = landline
row['date'] = datetime.strptime(row['date'], '%d %b %Y %H:%M: %S').strftime('%Y-%m-%d %H:%M:%S')
csv_output.writerow(row)