text = open('samiam.txt', 'r+')
keyword = " i "
keyword2 = "-i-"
replacement = " I "
replacement2 = "-I-"
for line in text:
if keyword in line:
text.write(line.replace(keyword, replacement))
print line
elif keyword2 in line:
text.write(line.replace(keyword2, replacement2))
print line
else:
print line
text.close()
我不完全确定为什么文本没有写入文件。帮忙?
使用^{} module 。(另请参见the MOTW site。)
使用
inplace
选项时,fileinput
模块重命名输入文件并将stdout重定向到具有原始文件名的新文件如果要保留每行右侧的空白,请不要
rstrip
,并使用print line,
(注意最后的逗号)输出处理过的行。这是因为你想同时读和写。尝试以下方法:
奖金:
更像是Python。
在你的代码中只需替换这一行
与
注意,这里我假设您正试图在文件末尾添加输出。一旦您读取了整个文件,文件指针就位于文件的末尾(即使您以
r+
模式打开了该文件)。因此,写操作实际上会写到文件的末尾,在当前内容之后。您可以通过在不同的行嵌入
text.tell()
来检查文件指针。下面是另一种方法:
相关问题 更多 >
编程相关推荐