简体   繁体   中英

How to swap rows and delete columns in csv python

This is my csv Input

,,A01.0 Брюшной тиф
0,"Тиф брюшной, Паратиф, Тиф, Паратифозная лихорадка",

output that I get after my code.

0,

this what I want to have and I have 11000 csv files like this one

"Тиф брюшной, Паратиф, Тиф, Паратифозная лихорадка",A01.0 Брюшной тиф
import csv

data = []
with open('/Users/gfidarov/Desktop/Python/CSV/synonims copy/syn8.csv') as inf:
    reader = csv.reader(inf)
    for row in reader:
        data.append(row)

with open('/Users/gfidarov/Desktop/Python/CSV/merged/syn.csv', 'w') as outf:
    writer = csv.writer(outf)
    writer.writerow([data[1][0], data[0][1]])
import csv


cols_to_remove = [0]# Column indexes to be removed (starts at 0)

cols_to_remove = sorted(cols_to_remove, reverse=True)# Reverse so we remove from the end first
row_count = 0# Current amount of rows processed

input_file = ('/Users/gfidarov/Desktop/Python/CSV/synonims copy/syn13.csv')
output_file = ('/Users/gfidarov/Desktop/Python/CSV/merged/syn.csv')
with open(input_file, "r") as source:
    reader = csv.reader(source)
    with open(output_file, "w", newline='') as result:
        writer = csv.writer(result)
        for row in reader:
            row_count += 1
            print('\r{0}'.format(row_count), end='') # Print rows processed
            for col_index in cols_to_remove:
                del row[col_index]
            writer.writerow(row)

with this code I can delete only one csv but I can't figure our how can do that with the entire folder

Question Concat 2 Rows of data and write selected columns

import csv, io

CSV = """,,A01.0 Data1
0,"Sentence 1",
,,A02.0 Data2
0,"Sentence 2",
,,A03.0 Data3
0,"Sentence 3",
"""

data = []
with io.StringIO(CSV) as inf:
    data = [record for record in csv.reader(inf)]

# concat every ziped pair of 2 lists into one list
data2 = [r[0] + r[1] for r in zip(data[0::2], data[1::2])]

with io.StringIO() as out_fh:
    writer = csv.writer(out_fh)
    for rec in data2:
        # Write only Column 4 and 2
        writer.writerow((rec[4], rec[2]))

    print(out_fh.getvalue())

Output :

 Sentence 1,A01.0 Data1 Sentence 2,A02.0 Data2 Sentence 3,A03.0 Data3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM