在每行的开头插入字符串 [英] Insert string at the beginning of each line
本文介绍了在每行的开头插入字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何在文本文件中每行的开头插入一个字符串,我有以下代码:
How can i insert a string at the beginning of each line in a text file, i have the following code:
f = open('./ampo.txt', 'r+')
with open('./ampo.txt') as infile:
for line in infile:
f.insert(0, 'EDF ')
f.close
我收到以下错误:
"文件对象没有属性'插入'"
"'file' object has no attribute 'insert'"
请注意,我是一个完整的程序n00b.
Please note that im a complete programming n00b.
推荐答案
Python随附包括电池:
import fileinput
import sys
for line in fileinput.input(['./ampo.txt'], inplace=True):
sys.stdout.write('EDF {l}'.format(l=line))
与已经发布的解决方案不同,这还保留了文件权限.
Unlike the solutions already posted, this also preserves file permissions.
这篇关于在每行的开头插入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文