简体   繁体   中英

how to swap rows in csv file with python?

I have 11k csv files where I have only two rows they look like this

---------------------------
             | A0.31       |
---------------------------
some data    |             |
---------------------------

and I want them in one only row

---------------------------
some data    | A0.31       |
---------------------------

I have this code but it just replaces the values not putting them in one row

import csv, os

with open('path/to/filename') as inf, open('path/to/filename_temp', 'w') as outf:
    reader = csv.reader(inf)
    writer = csv.writer(outf)
    for line in reader:
        if line[1] == '0':
           ...
        ... # as above

os.remove('path/to/filename')
os.rename('path/to/filename_temp', 'path/to/filename')

This should do the trick.

#!python
value=""
data=""
with open("test.csv","r") as inF, open("out.csv","w") as outF:
    lines= inF.readlines()
    for line in lines:
        if "-" in line:
            continue
        if line.isspace():
            continue
        fields=line.split("|")
        if not fields[1].isspace():
            value=fields[1]
        elif not fields[0].isspace():
            data=fields[0]
        else:
            continue
    outF.write("-------------------------------------\n")
    outF.write(data +"|" + value+ "|" +"\n")
    outF.write("-------------------------------------\n")

You indicate your files are CSV, so I'm going to assume your files are actually in CSV format, ie as follows:

,'A0.31'
'some data',

If your files are really that short, I would simply load both rows in the file, and immediately after that write the combined result to the same file:

import csv

data = []
with open('path/to/filename') as inf:
    reader = csv.reader(inf)
    for row in reader:
        data.append(row)

with open('path/to/filename', 'w') as outf:
    writer = csv.writer(outf)
    writer.writerow([data[1][0], data[0][1]])


This is my csv Input

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

output that I get after your code.

0,

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

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

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