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.

1

2 Answers 2

1

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

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

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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 You can, yes. Or a simple pip install bs4 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.