I have a text file contains Consecutive spaces, I need to replace them with a tabs
this is a part of the file:
this how I need it to be like:
I need to do it using python code or any easy and fast way place ^_^
I have a text file contains Consecutive spaces, I need to replace them with a tabs
this is a part of the file:
this how I need it to be like:
I need to do it using python code or any easy and fast way place ^_^
If you use an unix operation system you can use sed:
sed -r 's/[[:space:]]+/\t/g' input > output.txt
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.
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