0

I am making a find and replace script to fix some stuff on my website. I am using Python 3.3.2.

Here is my code:

import re

f = open('random.html', 'w')

strToSearch = " "

for line in f:
    strToSearch += line

patFinder1 = re.compile('<td>Sermon Title</td>\
            <td><audio preload="none" controls src="http://www.orlandobiblechurch.org/Audio/\d{6}ldm.mp3"></audio>\
            </td>\
        </tr>')

findPat1 = re.search(patFinder1, strToSearch)

findPat1 = re.findall(patFinder1, strToSearch)

for i in findPat1:
    print(i)

subFound = patFinder1.sub('<td>Lord\'s Day Morning</td>\
            <td><audio preload="none" controls src="http://www.orlandobiblechurch.org/Audio/\d{6}ldm.mp3"></audio>\
            </td>\
        </tr>', strToSearch)
print(subFound)

f.write(subFound)
f.close()

The problem is that python tells me that the file is not readable. If I changes this f = open('random.html', 'w') to f = open('random.html', 'r') to this, it says it is not writable. It makes sense why it needs both, but if I put both in, it tells me there must be exactly one read/write thing. I am positive that this is something basic, I just can't figure it out. Thanks for any help you can provide.

DogLover
  • 43
  • 1
  • 1
  • 5
  • 1
    Have you tried "w+"? I found this with a quick search: http://www.tutorialspoint.com/python/python_files_io.htm – erkmene Jul 24 '13 at 11:54

2 Answers2

1

f = open('random.html', 'r+')

Source: http://docs.python.org/3/tutorial/inputoutput.html

Jblasco
  • 3,827
  • 22
  • 25
0

You can use r+ or w+ as the second parameter to open it in both modes. Refer to here.

Also, have you considered using a with statement? They are more pythonic:

with open('random.html', 'w+') as f:
    do_stuff()

This has a great advantage that you don't need to manually do .close() afterwards.

  • strToSearch can also be re-written as strToSearch = ''.join(f.readlines())

  • Have you considered using a HTML parser such as BeautifulSoup for stuff like this? Better and easier than regex :)

TerryA
  • 58,805
  • 11
  • 114
  • 143
  • Hmm, Beautiful Soup looks interesting, but all the documentation talks about installing it on Ubuntu. I assume that I would simply click on the setup.py, right? – DogLover Jul 24 '13 at 12:21
  • @DogLover You can, yes. Or a simple `pip install bs4` :) – TerryA Jul 24 '13 at 12:22