繁体   English   中英

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

[英]How to reading .txt file , and 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

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

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

假设我的文件包含:

12345 678 91 011 12 1314

预期产量:

123 45 6 78 91 011 12 131 4

尝试这个。 请注意,这是我们关注的列位置/索引。 如您所说,该程序在索引2和3之间添加了一个空格。 您可以根据需要添加其他索引:

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[:3] + ' ' + line[3:]   # Add more indexes here
    newlines.append(newline)

with open("C:/path-to-file/file.txt", "w") as newfile:    
    newfile.write("\n".join(newlines))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM