繁体   English   中英

如何在文本文件的特定列位置添加或替换某些字符串

[英]How to add or replace some string at a particular column position in a text file

如何在文本文件的特定列位置添加或替换某些字符串:例如,在下面给出的特定文件示例中,我有一个句子:

Roxila almost lost
Roxila almost lost
Roxila almost lost
Roxila almost lost
Roxila almost lost

“ 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 

现在我想突变索引“ 6”,它是每行带有“ *”的“空格”。 像这样:

Roxila*almost lost

我该如何用python做到这一点。 请帮忙

您可以使用切片来获取新的字符串,然后使用fileinput模块来更新现有文件:

切片演示:

>>> s = "Roxila almost lost"
'Roxila almost lost'
>>> s [:6] + '*' + s[7:]
'Roxila*almost lost'

更新文件:

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

另一种方法,使用替换

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))

如果您的第一个字符串改变了,这意味着长度,在这种情况下切片将不起作用:

最好使用这种方式:

>>> s.split(' ')
['Roxila', 'almost', 'lost']
>>> p = s.split(' ')
>>> p[0]+'*'+' '.join(p[1:])
'Roxila*almost lost'
>>>

暂无
暂无

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

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