首页 > 解决方案 > Python加入csv的最后两个元素

问题描述

我有以下 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

标签: pythoncsvjoinmerge

解决方案


#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()

推荐阅读