[英]How to reading .txt file , and adding space after specific position / index for each line in 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.