[英]How to reading .txt file and rewriting by adding space after specific position / index for each line in python
[英]how to reading .txt file , and adding space after specific position/index , for each line in python
我想读取 txt.file 中的所有行,并在特定位置/索引之后添加空格。
假设我的文件包含:
1234567891011 12134516 17
在上面的文件中:我想在索引/位置 [8]、[10]、[16] 和 [20] 之后添加空格,表示在不规则位置/索引之后。
预期输出:
123456789 10 11 121 3451 6 17
提醒一下:我不想替换元素,只需在特定位置/索引后添加空格
注意:文件中的所有行都具有相同的结构。
读取和写入 .txt 文件并在特定位置/索引后添加空格。
我的文件包含:
1234567891011 12134516 17
6546546546456 35654554 54
预期输出:
123456789 10 11 121 3451 6 17
654654654 64 56 356 5455 4 54
您可以使用以下代码逐行读取文件并将输出放入数组中:
f=open('configuration.txt','r+')
lines=f.readlines()
现在您可以以字符串的形式访问每一行。 exp: line 0 by "lines[0]" 你可以在第 8 个索引中放置空格,如下所示:
lines[0]=lines[0][:8] + ' ' + lines[0][8:]
为了重写文件使用 "".join(lines) 将列表转换为字符串
f.write("".join(lines))
据我了解,以下代码将解决您的问题:
f=open('test.txt','r+')
lines=f.readlines()
for i in range(0,len(lines)):
if lines[i]=='\n':
continue
lines[i]=lines[i][:9] + ' ' + lines[i][9:]
lines[i]=lines[i][:12] + ' ' + lines[i][12:]
lines[i]=lines[i][:19] + ' ' + lines[i][19:]
lines[i]=lines[i][:24] + ' ' + lines[i][24:]
f.seek(0,0)
f.write("".join(lines))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.