【发布时间】:2019-08-30 13:02:23
【问题描述】:
我想读取 .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
【问题讨论】:
标签: python text-files readline