我需要能够打开一个 txt 文件,将其作为字符串读取,使用正则表达式替换字符串中的项目(摆脱非字母和数字字符),然后写入文件以便原始文件被“清理” 。”
这看起来很简单,但我是初学者,事实并非如此。我可以打开文件,在中间做所有的事情,并将更改保存到单个文件(使用 glob 和 re.sub),但无法弄清楚如何对原始文件进行更改并保存它。
所有帮助表示赞赏!第一次发帖谢谢。
我需要能够打开一个 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
另见:http ://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
对于 truncate([size]):http ://docs.python.org/2/library/stdtypes.html?highlight=truncate#file.truncate