使用正则表达式修改Python中的多个文件

时间:2013-08-26 01:59:50

标签: regex python-2.7 overwrite

我需要能够打开一个txt文件,将其作为字符串读取,使用正则表达式替换字符串中的项目(摆脱非字母和数字字符),然后写入文件使原始文件是"清理。"

这看起来很简单,但我是初学者而事实并非如此。我可以打开文件,在中间执行所有操作,并将更改保存到单个文件中(使用glob和re.sub),但无法弄清楚如何只更改原始文件并保存它。

所有帮助表示赞赏!第一次海报谢谢。

1 个答案:

答案 0 :(得分:0)

由于您似乎知道如何操作内容,因此我将为您提供一个处理文件的框架。

try:
    # 'r+' opens the file for both reading and writing
    with open("gg.txt", "r+") as f:
        # fetching the content
        content = f.read()
        # do your stuff here

        # writing back the content
        f.seek(0,0)
        f.write(content)
        f.truncate()
except EnvironmentError:
    print "oO"
    #better error handling here
    raise

另请参阅:http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

截断([size]):http://docs.python.org/2/library/stdtypes.html?highlight=truncate#file.truncate