在csv fi中将列数据分离为两个新列

2024-06-15 06:33:09 发布

您现在位置:Python中文网/ 问答频道 /正文

大家好

我正在写入一个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)      

Tags: csvtheto名称foroutputdatavalue
1条回答
网友
1楼 · 发布于 2024-06-15 06:33:09

最好使用csv.DictWriter()来创建CSV文件。可以使用正则表达式拆分call字段,以获得namelandline部分。然后可以将其添加到字典中,并使用.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)

相关问题 更多 >