使文件在Python中可读写

使文件在Python中可读写,python,Python,我正在做一个查找和替换脚本来修复我网站上的一些东西。我正在使用Python 3.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 preloa

我正在做一个查找和替换脚本来修复我网站上的一些东西。我正在使用Python 3.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()
重新导入
f=open('random.html','w')
strToSearch=“”
对于f中的行:
strToSearch+=行
patFinder1=re.compile('布道标题\
\
\
')
findPat1=重新搜索(patFinder1,strosearch)
findPat1=re.findall(patFinder1,strosearch)
对于findPat1中的i:
印刷品(一)
subFound=patFinder1.sub('上帝节早晨\
\
\
,strotsearch)
打印(子基金)
f、 写入(子基金)
f、 关闭()
问题是python告诉我该文件不可读。如果我把f=open('random.html','w')改为f=open('random.html','r'),它会说它不可写。为什么两者都需要,这是有道理的,但如果我把两者都放进去,它告诉我必须只有一个读/写东西。我肯定这是一件基本的事情,我就是想不出来。感谢您提供的帮助。

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

来源:

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


来源:

您可以使用
r+
w+
作为第二个参数,在两种模式下打开它。参考

另外,您是否考虑过使用带有语句的
?它们更像蟒蛇:

with open('random.html', 'w+') as f:
    do_stuff()
这有一个很大的优点,即您不需要在之后手动执行
.close()

  • strosearch
    也可以重新编写为
    strosearch=''.join(f.readlines())

  • 您是否考虑过使用HTML解析器来处理类似的内容?比正则表达式更好更简单:)


您可以使用
r+
w+
作为第二个参数在两种模式下打开它。参考

另外,您是否考虑过使用带有
语句的
?它们更像蟒蛇:

with open('random.html', 'w+') as f:
    do_stuff()
这有一个很大的优点,即您不需要在之后手动执行
.close()

  • strosearch
    也可以重新编写为
    strosearch=''.join(f.readlines())

  • 您是否考虑过使用HTML解析器来处理类似的内容?比正则表达式更好更简单:)


您尝试过“w+”吗?我通过快速搜索找到了这个:你试过“w+”吗?我通过快速搜索发现了这一点:嗯,BeautifulSoup看起来很有趣,但所有的文档都谈到了在Ubuntu上安装它。我想我只需点击setup.py,对吗?@DogLover你可以,是的。或者一个简单的
pip安装bs4
:)嗯,漂亮的汤看起来很有趣,但是所有的文档都在谈论在Ubuntu上安装它。我想我只需点击setup.py,对吗?@DogLover你可以,是的。或者一个简单的
pip安装bs4
:)