【问题标题】:python csv split row value, and new columnpython csv拆分行值和新列
【发布时间】:2020-06-17 10:44:42
【问题描述】:

我有一个 csv 文件,

    a         b              c
   text      text        2020/15 file  
   text      text        2020/12 file  
   text      text        2020/37 file  
   text      text        2020/25 file  

我想要输出(替换正则表达式拆分行值和新列),

    a         b              c             new column
   text      text        2020/15 file         15
   text      text        2020/12 file         12 
   text      text        2020/37 file         37
   text      text        2020/25 file         25

我该怎么做,请帮帮我,谢谢

【问题讨论】:

  • 欢迎来到Stack OverflowIt appears no attempt was made.edit 您的问题包括您尝试过的内容。
  • 你有没有尝试解决这个问题?
  • 不,因为我不知道使用哪种方法,我不想要代码,可能是一个链接,我正在寻找我的问题,但我没有找到解决的答案

标签: python csv


【解决方案1】:

此代码将满足您的需求。读取一个名为 old.csv 的 csv,并在同一文件夹中以您的格式创建 new.csv。

Mark Solved,在这里提问之前先做一些锻炼....

import csv,re
def find_number(text, c):
    return re.findall(r'%s(\d+)' % c, text)
col1, col2, col3, col4 = [], [], [], []
with open("Old.csv",'rt')as f: #csv file name
  data = csv.reader(f)
  for row in data:
      col1.append(row[0])
      col2.append(row[1])
      col3.append(row[2])
for _ in col3:#extracting /
    col4.extend(find_number(_, "/"))

rows = zip(col1,col2,col3,col4)
with open('New.csv', 'w') as csvfile:
    csvwriter = csv.writer(csvfile)
    for row in rows:
        csvwriter.writerow(row)

【讨论】:

  • 请接受答案@eroniko 点击代码左侧的勾选。让每个人都知道这是一个公认的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-15
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-09
  • 1970-01-01
相关资源
最近更新 更多