【问题标题】:Read the content of the .csv and write it in an other .csv file using python [closed]读取 .csv 的内容并使用 python 将其写入另一个 .csv 文件 [关闭]
【发布时间】:2019-01-11 09:20:32
【问题描述】:

如何读取 csv 文件的每一行并使用 python 将其写入另一个 csv 文件?

【问题讨论】:

  • 你已经尝试了什么?
  • 为什么不直接复制文件呢?成为 CSV 与任何事情有什么关系?

标签: python csv


【解决方案1】:

一个简单的解决方案:读取并拆分每一行,然后再将其写入另一个 csv 文件。

def filter(source, destination):
    fs = open(source, 'r')
    fd = open(destination, 'w')
    txt = fs.readline()
    while txt:
       txt1 = txt.split(',')
       txt2 = txt1[0]+','+txt1[1]
       fd.write(txt2+'\n')
       txt = fs.readline()
    fs.close()
    fd.close()

如果 name == 'ma​​in':
过滤器(r'C:\source.csv', r'C:\destination.csv')

【讨论】:

    【解决方案2】:

    它是 csv 真的很重要吗?听起来你可以逐行写

    with open('csvtowriteto', 'wb') as writer:
        with open('csvtoreadfrom', 'rb') as reader:
            for line in reader:
                writer.write(line)    
    

    【讨论】:

      猜你喜欢
      • 2019-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-18
      • 1970-01-01
      • 2023-01-10
      • 1970-01-01
      相关资源
      最近更新 更多