问题描述
因此,正如描述所描述的,我想按顺序将文本添加到文件中.说,例如,我有一个这样的文件(不是HTML,这只是一种虚构的语言),可以将其命名为ALLTHEITEMS:
So as the description describes, I would like to add text to a file in a sequential manner. Say, for example I have a file like this (NOT HTML, this is just an imaginary language) lets call it ALLTHEITEMS:
<items>
</items>
说另一个名为ITEMS的文件:
say another file named ITEMS:
banana
apple
blueberry
pickle
我已经通读了项目并创建了一个数组:['banana','apple','blueberry','pickle']
And I already have read through items and have an array created:['banana','apple','blueberry','pickle']
我想遍历数组中的每个项目并将其写入标签之间的ALLTHEITEMS.
I want to go through each item in the array and write it to ALLTHEITEMS in between the tags.
所以最终ALLTHEITEMS应该看起来像:
So in the end ALLTHEITEMS should look like:
<items>
banana
apple
blueberry
pickle
</items>
最Python的方式是什么?
What is the most pythonic way?
推荐答案
我会这样:
with open(outputfile,'w') as out, open(inputfile) as f:
for line in f:
out.write(line)
if tag_match(line): #Somehow determine if this line is a match where we want to insert text.
out.write('\n'.join(fruits)+'\n')
您可能提出了一种使速度更快的方法,但我怀疑这样做是否值得.这很简单,易于阅读,可以完成工作. "pythonic"对我来说足够了:-)
You might come up with a way to make it faster, but I doubt it is worthwhile. This is simple, easy to read, and gets the job done. "pythonic" enough for me :-)
这篇关于将行插入文件的Python方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!