Python 如何在文本文件中的特定列位置添加或替换某些字符串
如何在文本文件中的特定列位置添加或替换某些字符串: 例如,我在下面给出的特定文件示例中有一句话:Python 如何在文本文件中的特定列位置添加或替换某些字符串,python,string,file,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
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实现这一点。请提供帮助您可以使用切片来获取新字符串和
文件输入
模块来更新现有文件:
for line in f:
line = line.rstrip()
newline = line[:6] + '*' + line[7:]
print newline
切片演示:
>>> 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:],
另一种方法是使用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))
如果您的第一个字符串发生了更改(即长度),那么切片将无法工作: 最好采用这种方式:
>>> s.split(' ')
['Roxila', 'almost', 'lost']
>>> p = s.split(' ')
>>> p[0]+'*'+' '.join(p[1:])
'Roxila*almost lost'
>>>