Pythonic way of inserting lines to a file

2019-02-26 08:32发布

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>

say another file named ITEMS:

banana
apple
blueberry
pickle

And I already have read through items and have an array created:['banana','apple','blueberry','pickle']

I want to go through each item in the array and write it to ALLTHEITEMS in between the tags.

So in the end ALLTHEITEMS should look like:

<items>
banana
apple
blueberry
pickle
</items>

What is the most pythonic way?

2条回答
▲ chillily
2楼-- · 2019-02-26 09:04

I would do it like this:

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

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

查看更多
smile是对你的礼貌
3楼-- · 2019-02-26 09:15

The most pythonic way for parsing markup is to use a suitable module to parse it.

查看更多
登录 后发表回答