Search code examples
pythonfilevimformatfwrite

Inserting spaces " " into a table file using Python to separate columns


I have a table file that looks like this:

3 5415.00    6.00 -1998.3 -781.28 21.98 9.99 3.41  21.63 0.94 1.29 0 -98.04  98.04
4 6443.00    6.00 -1998.3-1216.10 21.71 0.35 0.38  22.78 8.00 3.00 2 -98.04  98.04
5 5806.00    7.00 -1997.8 -946.67 21.04 0.19 0.19  23.26 6.27 0.97 0   2.23  -2.23
6 7882.00    8.00 -1997.4-1824.80 22.18 0.58 0.49  22.62 0.85 0.85 0   0.44  -0.44
7 3278.00    9.00 -1997.0  122.67 20.94 0.24 0.20  23.53 8.00 0.24 2 -98.04  98.04

As you can see there are certain values that exceed the expected space it should take and get rid of the space between the columns, causing my code unable to read the file, stating there are less columns than the rest.

An advantage is that I can know in which exact columns (may happen in several) of the file this happens, so I can implement a code or function that inserts a space into these columns to every line of the file.

I'm not very familiar with writing/reading files, so I'm guessing the thought above is the simplest way to solve this. Cheers.


Solution

  • The way I see it, if you don't know exactly where all the "mistakes" are, you're going to have to read the entire file anyway.

    Insofar as that's true, I'd say that your approach (to go and add a space in every line at column n) is actually pretty efficient.

    I'd also suggest looking into Vim's blockwise visual mode. For example (modified from jubi):

    1. Go to the column you need to
    2. Ctrl + v (to enter in visual mode)
    3. Use the arrow keys to select the lines
    4. Shift + i (takes you to insert mode)
    5. Hit space keys or whatever you want to type in front of the selected lines.
    6. Save the changes (Use :w) and now you will see the changes in all the selected lines.

    Here's another source: How to insert a block of white spaces starting at the cursor position in vi?

    Hope it works!