How to reading .txt file and rewriting by adding space after specific position / index for each line in python

前端 未结 2 1594
感动是毒
感动是毒 2021-01-27 06:32

I want to read .txt file and add space after a specific position/index for each line. please consider below example for more details.

suppose my file contains

2条回答
  •  無奈伤痛
    2021-01-27 07:26

    Consider this:

    space_indecies = [2, 5, 8]
    
    with open("C:/path-to-file/file.txt", "r") as file:
        lines = file.read().split("\n")
    newlines = []
    for line in lines:
        line = line.rstrip()
        for n, i in enumerate(space_indecies):
            line = line[:i + n] + ' ' + line[n + i:]
        newlines.append(line)
    with open("C:/path-to-file/file.txt", "w") as newfile:  
        newfile.write("\n".join(newlines))
    
    

    The i + n is needed, because the index where you want to insert your space shifts with every space inserted

提交回复
热议问题