Python объединить два последних элемента CSV - PullRequest
0 голосов
/ 29 апреля 2020

У меня есть файл 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

Ответы [ 3 ]

0 голосов
/ 29 апреля 2020
test2,2020-04-28,00,:15

Если ваш файл выглядит именно так, вы можете просто заменить ,: на : строка за строкой для всего файла сразу.

Нет необходимости анализировать каждый файл поле отдельно.

0 голосов
/ 29 апреля 2020

Вы можете использовать модуль CSV :

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
0 голосов
/ 29 апреля 2020
#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()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...