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

时间:2014-02-03 10:02:29

标签: python string 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做到这一点。请帮忙

4 个答案:

答案 0 :(得分:1)

您可以使用切片来获取新字符串和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:],

答案 1 :(得分:0)

for line in f:
   line = line.rstrip()
   newline = line[:6] + '*' + line[7:]
   print newline

答案 2 :(得分:0)

另一种方法,使用替换

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

答案 3 :(得分:0)

如果您的第一个字符串更改,这意味着长度,那么切片不会起作用:

最好以这种方式使用:

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