本文主要是介绍[Python] 先读后覆盖写文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Python先读后覆盖写文件
只打开一次文件,先把文件内容读取出来,处理之后形成新的数据,重新写入新的数据,完成先读取后覆盖写文件。
比如有一个文件内容如下,需要将内容全转为大写然后覆盖:
Now York is 3 hours ahead of California, but it does not make California slow.
Someone graduated at the age of 22, but waited 5 years before securing a good job.
Someone became a CEO at 25, but died at 50.
While another became a CEO at 50, and lived to 90.
Someone is still single, while someone else got married.
Abselutely everyone in this world works based on the Time Zone.
先读取文件,然后覆盖:
def rewrite_file(file_path):with open(file_path, mode='r+', encoding='utf-8') as f:# 先读取文件, 将文件指针指向开始,并使用truncate()清除所有内容data = f.read()f.seek(0)f.truncate()data = upper_data(data) # 将所有数据转为大写f.write(data) # 重写数据# 重读数据f.seek(0)print(f.read())def upper_data(data):return data.upper()if __name__ == '__main__':rewrite_file('zone.txt')
输出如下:
NOW YORK IS 3 HOURS AHEAD OF CALIFORNIA, BUT IT DOES NOT MAKE CALIFORNIA SLOW.
SOMEONE GRADUATED AT THE AGE OF 22, BUT WAITED 5 YEARS BEFORE SECURING A GOOD JOB.
SOMEONE BECAME A CEO AT 25, BUT DIED AT 50.
WHILE ANOTHER BECAME A CEO AT 50, AND LIVED TO 90.
SOMEONE IS STILL SINGLE, WHILE SOMEONE ELSE GOT MARRIED.
ABSELUTELY EVERYONE IN THIS WORLD WORKS BASED ON THE TIME ZONE.
如果文件过大怎么办?
推荐你使用生成器读取文件后写入,可以按行处理或者按块处理,思路是一样的。
如何使用生成器读写文件,参考[Python] 三种文件读取方式:生成器分块/按行/一次读取
这篇关于[Python] 先读后覆盖写文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!