2

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?

E.Cross
  • 2,087
  • 5
  • 31
  • 39
  • Show your way of doing that and we will tell you how to improve it. – Tomasz Wysocki Aug 20 '12 at 20:52
  • What is the end goal? Should they be separated with newlines, like `banana\napple\nblueberry\npickle\n`, or stored some other way? – David Robinson Aug 20 '12 at 20:53
  • The goal is to have the file to look like: banana apple blueberry pickle – E.Cross Aug 20 '12 at 20:54
  • Have you looked at the [mmap module](http://docs.python.org/library/mmap.html)? I'd expect that if for whatever reason you can't just read the contents into a string, append to the string and then overwrite file with the whole shebang, mmap and regexes would be the way to go... – chucksmash Aug 20 '12 at 20:55
  • @TomaszWysocki It would be simple with a sed command, or in python for each item, I read ALLTHEITEMS line by line until I match and then somehow write below that line the item. – E.Cross Aug 20 '12 at 21:00

2 Answers2

6

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

mgilson
  • 300,191
  • 65
  • 633
  • 696
0

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

eminor
  • 923
  • 6
  • 11
  • 1
    There are no modules for a language that does not exist. Its a configuration file to be exact. – E.Cross Aug 20 '12 at 21:21
  • @Dan Do you control the config file format (is it a custom app)? There are a billion formats for config files (`ini`, `json`, `yaml`, you name it) - there are modules for these, and no reason to not use these formats if you can. – Thomas Orozco Aug 20 '12 at 21:30