Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 使用正则表达式修改Python中的多个文件_Regex_Python 2.7_Overwrite - Fatal编程技术网

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

Regex 使用正则表达式修改Python中的多个文件,regex,python-2.7,overwrite,Regex,Python 2.7,Overwrite,我需要能够打开一个txt文件,将其作为字符串读取,使用正则表达式替换字符串中的项目(去掉非字母和数字字符),然后写入文件,以便“清理”原始文件 这看起来很简单,但我是个初学者,事实并非如此。我可以打开文件,在中间执行所有操作,并将更改保存到单个文件中(使用glob和re.sub),但我不知道如何对原始文件进行更改并保存它 感谢大家的帮助!第一次海报谢谢 由于您似乎知道如何操作内容,我将为您提供一个处理文件的框架 try: # 'r+' opens the file for both re

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

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


感谢大家的帮助!第一次海报谢谢

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

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
另见:


对于截断([size]):

谢谢。我要试一试,让你知道发生了什么事!