pythonfilereplacespacetap

Replace space with tab in entire text file python


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 ^_^


Solution

  • 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.