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

青春壹個敷衍的年華 提交于 2019-12-13 03:48:43

问题


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

12345 678 91011 12 1314

In the above file, the first row contains space after a specific position/index [4] , then after position/index[8], after position/index[14] and after position/index[17]

Expected output : I want every row in the file is having space after a specific position. i.e for the first row, I want to add space after index [2], then add space after index [6], then add space after index[11], then add space after index [21], and so on...

123 45 6 78 91 011 12 131 4

As a reminder, I don't want to replace elements but add a new space after a specific position/index.

reading .txt file and add space after a specific position/index, for each line in python.

with open("C:/path-to-file/file.txt", "r") as file:
    lines = file.read().split("\n")
    newlines = []
    for line in lines:
        line = line.rstrip()
        newline = line[:] + ' ' + line[:]   # this line is incorrect
        newlines.append(newline)
    with open("C:/path-to-file/file.txt", "w") as newfile:  
        newfile.write("\n".join(newlines)

add space after a specific position/index for each line a text file

suppose my file contains :

12345 678 91 011 12 1314

Expected output :

123 45 6 78 91 011 12 131 4


回答1:


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




回答2:


Here is another solution using generator expressions.

If you are happy to provide the list of indices after each space rather than before, this will do the job:

line = '12345 678 91011 12 1314'
idx = [3, 7, 12, 22]
' '.join([line[i:j] for i, j in zip([None]+idx, idx+[None])])

which gives '123 45 6 78 91 011 12 131 4'.

Otherwise you would need to first add one to each index:

idx = [2, 6, 11, 21]
idx = [i+1 for i in idx]


来源:https://stackoverflow.com/questions/57727283/how-to-reading-txt-file-and-rewriting-by-adding-space-after-specific-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!