【问题标题】:Python join two last elements of a csvPython加入csv的最后两个元素
【发布时间】:2020-08-13 15:04:35
【问题描述】:

我有以下 CSV 文件,我想合并最后 2 列。有什么想法吗?

current    
test1,2020-04-28,00,:00
test2,2020-04-28,00,:15
test3,2020-04-28,00,:30
test4,2020-04-28,00,:45

wanted
test1,2020-04-28,00:00
test2,2020-04-28,00:15
test3,2020-04-28,00:30
test4,2020-04-28,00:45

【问题讨论】:

  • 到目前为止你尝试过什么?请发布您的代码。

标签: python csv join merge


【解决方案1】:

您可以使用csv module:

import csv 

with open(your_file) as csv_in:
    for row in csv.reader(csv_in):
        row[2]+=row[3]
        del row[3]
        print(row)

打印:

['test1', '2020-04-28', '00:00']
['test2', '2020-04-28', '00:15']
['test3', '2020-04-28', '00:30']
['test4', '2020-04-28', '00:45']

您可以同时将 csv 写入新文件,而不是打印:

with open(your_file) as csv_in, open(your_new_file, 'w') as csv_out:
    writer=csv.writer(csv_out)
    for row in csv.reader(csv_in):
        row[2]+=row[3]
        del row[3]
        writer.writerow(row)

your_new_file 变为:

test1,2020-04-28,00:00
test2,2020-04-28,00:15
test3,2020-04-28,00:30
test4,2020-04-28,00:45

【讨论】:

    【解决方案2】:
    #Declare the files you are working with.
    #infile is the file to read from (original data)
    inFile = open(pathToInFile,'r') 
    #outFile is the file to write new data to.
    outFile= open(pathToOutFile,'w')
    
    #We are reading the file in a text mode.
    #So, in this case, for each line in the original data
    for line in inFile:
        #split the line on the comma
        line = line.split(',')
        #make a new list of elements
        #0,1, 2+3 -- that is, 
        #['test4', '2020-04-28', '00:45']
        #the plus operand on line[2] and [3] 
        #concatenates em
        line = line[0:2] + [line[2]+line[3]] 
        #Join the entire list with commas
        #as a way of prepping the line for 
        #writing to file as text
        line = ','.join(line)
        #write to file
        outFile.write(line)
    inFile.close()
    outFile.close()
    

    【讨论】:

      【解决方案3】:
      test2,2020-04-28,00,:15
      

      如果您的文件看起来完全一样,您可以一次将整个文件的 ,: 逐行替换为 :

      不需要单独解析每个字段。

      【讨论】:

        猜你喜欢
        • 2018-03-27
        • 2012-07-31
        • 2020-04-04
        • 1970-01-01
        • 2020-08-19
        • 2021-12-01
        • 2014-08-15
        • 2020-03-05
        • 1970-01-01
        相关资源
        最近更新 更多