简体   繁体   中英

Edit columns in a text file

I have a text file containing 4 columns. I need to remove the first two columns and replace them with one column. The value which I should put as the new column is being produced in a loop. Here is something I am trying to do.

The input is like this:

   1 2 3 4
   5 6 7 8
   9 1 2 3

The output should be like this:

d 3 4
d 7 8
d 2 3

but "d" is a variable that is being produced in a loop for each line.

with open('EQ.txt','r') as f:
    i = 0
    for line in f
...
...
d=r+d
with open(c.txt, "w") as wrt:
new_line = d\n.format(line[2], line[3])
wrt.write(new_line)

What you want is:

new_line = "%d %d %d\n".format(d, line[2], line[3])

The format string has to be in quotes, with %d formats to specify that you want decimal numbers there. Then you list all three values in the argument list.

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