Edit Tukar Kolom/Baris CSV File tanpa library apapun di Python

Bagaimana cara edit CSV file tanpa library khususnya menukar kolom ID yang tertukar seperti dibawah ini tanpa library apapun di python?
udah banyak nyari tapi make lib pandas, dll gituScreenshot-2021-11-09-214146.pngScreenshot 2021-11-09 214146.png
avatar faishalyusufbaqir

@faishalyusufbaqir

1 Kontribusi 0 Poin


Jawaban

# cara pertama: ubah manual

# cara kedua: programmatically, dengan asumsi bahwa kolom apapun didapatkan nilai ID didalamnya akan ditukar dengan nilai apapun pada kolom ID tetap
import re

data = open('./tes.csv')
new_data = open('./new_tes.csv', mode='w')
line = data.readline()  # header
new_data.write(line)
line = data.readline()  # first row
while line:
    items = line.strip().split(',')
    for i in range(len(items)):
        if re.match(pattern=r'\d{4,}', string=str(items[i].strip())) and i == 0:
            break
        if re.match(pattern=r'\d{4,}', string=str(items[i].strip())):
            items[0], items[i] = items[i], items[0]
            break
    new_s = ', '.join(items)
    new_s = new_s.strip()
    new_data.write(new_s)
    new_data.write('\n')
    line = data.readline()
data.close()
new_data.close()

# cara ketiga: programmatically menggunakan teknik rotasi (based on assumption)
data = open('./tes.csv')
new_data = open('./new_tes2.csv', mode='w')
line = data.readline()  # header
new_data.write(line)
line = data.readline()  # first row
while line:
    items = line.strip().split(',')
    for i in range(len(items)):
        if re.match(pattern=r'\d{4,}', string=str(items[i].strip())) and i == 0:
            break
        if re.match(pattern=r'\d{4,}', string=str(items[i].strip())):
            new_items = ['' for _ in range(len(items))]
            j = 0
            a = i
            while j < len(new_items)-i:
                new_items[j] = items[a].strip()
                j += 1
                a += 1
            k = 0
            while k < i:
                new_items[j] = items[k].strip()
                k += 1
                j += 1
            items = new_items
            break

    new_s = ', '.join(items)
    new_s = new_s.strip()
    new_data.write(new_s)
    new_data.write('\n')
    line = data.readline()
data.close()
new_data.close()

avatar MSalsabilaJamil

@MSalsabilaJamil

4 Kontribusi 0 Poin


Login untuk gabung berdiskusi