大家好
我正在写入一个csv文件,我需要将一列的信息分为两列 例如:
Call
Goku (1000)
有这样的东西:
Name Landline
Goku 1000
因此,我需要帮助删除括号周围的号码,只采取其中的号码,而重命名的呼叫列标题名称,然后创建一个新的列称为座机前写其他列,名称和座机需要是前两列,然后其他人跟着。你知道吗
我有以下代码:
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)
最好使用
csv.DictWriter()
来创建CSV文件。可以使用正则表达式拆分call
字段,以获得name
和landline
部分。然后可以将其添加到字典中,并使用.writerow()
调用编写:相关问题 更多 >
编程相关推荐