python - 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
解决方案
#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()
推荐阅读
- json - JSON解析[`jq`]:获取祖父母兄弟姐妹的值
- python - df.fillna 或 df.replace 没有消除我的 .csv 文件中的 NaN
- ios - 在按钮外开始触摸并在拖入按钮边界时触发事件
- javascript - 将变量传递给ajax时django中的TemplateSyntaxError
- android - phonegap ajax 请求在 http 中不起作用
- python-3.x - 有没有办法反向查看我的 md5 哈希码?
- html - 尽管同时使用了边距和填充功能,但 CSS 背景边距不起作用
- node.js - 将对象数组放入 dynamoDB
- python - 如果有多个条件无法弄清楚
- c# - 不注册已移除的子对象