如何读取.txt文件并通过在python中每行的特定位置/索引后添加空格来重写 [英] How to reading .txt file and rewriting by adding space after specific position / index for each line in python

查看:258
本文介绍了如何读取.txt文件并通过在python中每行的特定位置/索引后添加空格来重写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取 .txt 文件并在每行的特定位置/索引后添加空格.请考虑以下示例以了解更多详细信息.

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

假设我的文件包含

12345 678 91011 12 1314

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

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]

预期输出:我希望文件中的每一行在特定位置后都有空间.即对于第一行,我想在索引 [2] 之后添加空格,然后在索引 [6] 之后添加空格,然后在索引 [11] 之后添加空格,然后在索引 [21] 之后添加空格,依此类推...

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.

读取 .txt 文件并在特定位置/索引后为 python 中的每一行添加空格.

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

假设我的文件包含:

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 是必需的,因为您要插入空格的索引会随着每个空格的插入而移动

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

这篇关于如何读取.txt文件并通过在python中每行的特定位置/索引后添加空格来重写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆