【问题标题】:Making File Writable and Readable in Python在 Python 中使文件可写和可读
【发布时间】:2013-07-23 21:12:32
【问题描述】:

我正在制作一个查找和替换脚本来修复我网站上的一些内容。我正在使用 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()

问题是python告诉我文件不可读。如果我将此 f = open('random.html', 'w') 更改为 f = open('random.html', 'r') ,则表示它不可写。为什么它需要两者是有道理的,但如果我把两者都放进去,它告诉我必须只有一个读/写的东西。我很肯定这是基本的东西,我只是想不通。感谢您提供的任何帮助。

【问题讨论】:

标签: python


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    另外,您是否考虑过使用with 语句?他们更pythonic:

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

    这有一个很大的好处,就是以后不用手动.close()了。

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

    • 您是否考虑过使用诸如BeautifulSoup 之类的HTML 解析器来处理此类问题?比正则表达式更好更容易:)

    【讨论】:

    • 嗯,Beautiful Soup 看起来很有趣,但所有文档都谈到在 Ubuntu 上安装它。我假设我只需点击 setup.py,对吧?
    • @DogLover 你可以,是的。或者一个简单的pip install bs4 :)
    猜你喜欢
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 2016-08-07
    • 2012-11-12
    • 1970-01-01
    • 2013-04-09
    • 2011-08-12
    • 2021-06-26
    相关资源
    最近更新 更多