[英]How to add or replace some string at a particular column position in a text file
How to add or replace some string at a particular column position in a text file: for example i have one sentence in a particular file example given below: 如何在文本文件的特定列位置添加或替换某些字符串:例如,在下面给出的特定文件示例中,我有一个句子:
Roxila almost lost
Roxila almost lost
Roxila almost lost
Roxila almost lost
Roxila almost lost
"enumerate()" gives some thing like this “ enumerate()”给出了类似的东西
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
R o x i l a a l m o s t l o s t
now i want to mutate index "6" which is a "space" with "*" at each row. 现在我想突变索引“ 6”,它是每行带有“ *”的“空格”。 like this: 像这样:
Roxila*almost lost
how can i do this with python. 我该如何用python做到这一点。 Please help 请帮忙
You can use slicing to get a new string and fileinput
module to update the existing file: 您可以使用切片来获取新的字符串,然后使用fileinput
模块来更新现有文件:
Slicing demo: 切片演示:
>>> s = "Roxila almost lost"
'Roxila almost lost'
>>> s [:6] + '*' + s[7:]
'Roxila*almost lost'
Updating the file: 更新文件:
import fileinput
for line in fileinput.input('foo.txt', inplace=True):
print line[:6] + '*' + line[7:],
for line in f:
line = line.rstrip()
newline = line[:6] + '*' + line[7:]
print newline
Another approach, using replace 另一种方法,使用替换
with open("yourfile.txt", "r") as file:
lines = file.read().split("\n")
newlines = []
for line in lines:
newline = line.replace(" ", "*", 1)
newlines.append(newline)
with open("newfile.txt", "w") as newfile:
newfile.write("\n".join(newlines))
If your first string change, which means the length, in that case slicing won't work: 如果您的第一个字符串改变了,这意味着长度,在这种情况下切片将不起作用:
Better to use this way: 最好使用这种方式:
>>> s.split(' ')
['Roxila', 'almost', 'lost']
>>> p = s.split(' ')
>>> p[0]+'*'+' '.join(p[1:])
'Roxila*almost lost'
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.