簡體   English   中英

如何讀取.txt文件並通過在python中的每一行的特定位置/索引后添加空格來重寫

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

我想讀取.txt文件,並在每行的特定位置/索引后添加空格。 請考慮以下示例以了解更多詳細信息。

假設我的文件包含

12345 678 91011 12 1314

在上面的文件中,第一行在特定位置/索引[4]之后,在位置/索引[8]之后,在位置/索引[14]之后和在位置/索引[17]之后包含空格

預期的輸出:我希望文件中的每一行在特定位置后都有空格。 即對於第一行,我想在索引[2]之后添加空間,然后在索引[6]之后添加空間,然后在索引[11]之后添加空間,然后在索引[21]之后添加空間,依此類推...

123 45 6 78 91 011 12 131 4

提醒一下,我不想替換元素,而是在特定位置/索引之后添加新的空格。

讀取.txt文件,並在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)

在每行文本文件的特定位置/索引后添加空格

假設我的文件包含:

12345 678 91 011 12 1314

預期產量:

123 45 6 78 91 011 12 131 4

考慮一下:

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))

i + n是必需的,因為要插入空間的索引隨插入的每個空間而變化

這是使用生成器表達式的另一種解決方案。

如果您願意每個空格之后而不是之前提供索引列表,則可以完成以下工作:

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

給出'123 45 6 78 91 011 12 131 4'

否則,您需要先向每個索引添加一個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM