user3262968
user3262968

Reputation: 15

Adding Hyphen in row data in python

In my csv file, i have a col with value like A12001 A22001 A32001

I need to make it look like

A1-2001 A2-2001 A3-2001

I am new to python. Any help will be appreciated.

Thanks

Upvotes: 0

Views: 511

Answers (2)

Iron Fist
Iron Fist

Reputation: 10951

I'm not sure how you CSV file is made of, so for simplicity sake I will assume that your CSV file has only this column.

So,

1 - Open your CSV file for read & write, assuming its name myCSV.csv

2 - read each line and re-write it with the modified string.

3 - Close the CSV file

with open('myCSV.csv','rb+') as f:
    while True:
        line = f.readline()
        if not line: break #Break of While loop when reaching EOF(End Of File)
        f.seek(-len(line),1) #Set current file position to beginning of current line
        line = line[:2] + '-' + line[2:] #modify your string
        f.write(line) #write modified line
        f.flush() #make the write happen

Upvotes: 1

James
James

Reputation: 36643

For each string value sv in the column you can use

newval = sv[:2] + '-' + sv[2:]

Upvotes: 0

Related Questions