python - Change values in CSV or text style file -


i'm having problems following file. each line has following content:

foobar   1234.569    7890.125     12356.789   -236.4569   236.9874   -569.9844 

what want edit in file, reverse last 3 numbers, positive or negative. output should be:

foobar   1234.569    7890.125     12356.789   236.4569   -236.9874   569.9844 

or better:

foobar,1234.569,7890.125,12356.789,236.4569,-236.9874,569.9844 

what easiest pythonic way accomplish this? @ first used csv.reader, found out it's not tab separated, random (3-5) spaces. i've read csv module , examples / similar questions here, knowledge of python ain't , csv module seems pretty tough when want edit value of row. can import , edit in excel no problem, want use in python script, since have hundreds of these files. vba in excel not option.

would better regex each line? if so, can point me in direction example?

you can use str.split() split white-space-separated lines row:

row = line.split() 

then use csv.writer() create new file.

str.split() no arguments, or none first argument, splits on arbitrary-width whitespace , ignores leading , trailing whitespace on line:

>>> 'foobar   1234.569    7890.125     12356.789   -236.4569   236.9874   -569.9844\n'.split() ['foobar', '1234.569', '7890.125', '12356.789', '-236.4569', '236.9874', '-569.9844'] 

as complete script:

import csv  open(inputfilename, 'r') infile, open(outputcsv, 'wb') outfile:     writer = csv.writer(outfile)      line in infile:         row = line.split()         inverted_nums = [-float(val) val in row[-3:]]         writer.writerow(row[:-3] + inverted_nums) 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -