-1

I have a text file contains Consecutive spaces, I need to replace them with a tabs

this is a part of the file:

enter image description here

this how I need it to be like:

enter image description here

I need to do it using python code or any easy and fast way place ^_^

dejanualex
  • 3,872
  • 6
  • 22
  • 37
  • Note that it's called *tab*, not tap. – MisterMiyagi Jun 20 '20 at 11:10
  • 1
    Welcome to [so]. Please be aware this is not a code-writing service. We can help solving specific, technical problems, not open-ended requests for code or advice. Please [edit] your question to show what you have tried so far, and what specific problem you need help with. See the [ask] page for details how to help us help you. – MisterMiyagi Jun 20 '20 at 11:11

3 Answers3

0

If you use an unix operation system you can use sed:

sed -r 's/[[:space:]]+/\t/g' input > output.txt
Alexander Kosik
  • 669
  • 3
  • 10
0

Here a solution with python as you requested:

filepath_in = 'path/to/my/filein.txt'
filepath_out = 'path/to/my/fileout.txt'
with open(filepath_in, 'r') as file_in, open(file_path_out, 'w') as file_out:
    for line in file_in:
        data = line.split()  # splits the content removing spaces and final newline
        line_w_tabs = "\t".join(data) + '\n'
        file_out.write(line_w_tabs)

Pay attention that if the content of a cell of data is long compared to others in the same column, one tab may not be enough and your table may be not well aligned.

If layout is important you would need some manipulation, you could consider using python format or even some library.

piertoni
  • 1,933
  • 1
  • 18
  • 30
0

Lets say, The original file is named as demo.txt and the content looks below.

$ cat "demo.txt"

id name  work address
1 sam google USA
2 raman facebook Europe

Read the file and store all the rows in a list. Find the longest word to keep the even space between all the columns. "ljust" is being used to justify the words (to maintain the even spaces between values)

Below is the code snippet.

>>> file = "demo.txt"
>>> f = open(file, "r")
>>> data = f.readlines()
>>> col_width = max(len(word) for row in data for word in row.split()) + 2  # padding
>>> for row in data:
...     print "".join(word.ljust(col_width) for word in row.split())
...

id         name       work         address
1          sam        google       USA
2          raman      facebook     Europe
Surajit Mitra
  • 414
  • 8
  • 15