使文件在Python中可读写

2024-06-06 09:40:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个查找和替换脚本,以修复我的网站上的一些东西。我正在使用Python3.3.2。

这是我的代码:

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

问题是python告诉我文件不可读。如果我将这个f=open('random.html','w')改为f=open('random.html','r'),它会说它是不可写的。它需要两者的原因是有道理的,但是如果我把两者都放进去,它会告诉我必须只有一个读/写的东西。我很肯定这是最基本的,我就是想不出来。谢谢你的帮助。


Tags: inrenoneforhtmllinerandomopen
2条回答

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

来源:http://docs.python.org/3/tutorial/inputoutput.html

您可以使用r+w+作为第二个参数以两种模式打开它。请参阅here

另外,您是否考虑过使用with语句?它们更像Python:

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

这有一个很大的优势,你不需要手动做.close()之后。

  • strToSearch也可以重写为strToSearch = ''.join(f.readlines())

  • 你有没有考虑过用一个HTML解析器比如^{}来处理这样的事情?比regex更好、更容易:)

相关问题 更多 >