修改文件(通常使用第二种)

# 1. 简单直接粗暴的方式

# f = open("stus.txt",encoding="utf-8")
# content = f.read()
# content = content.upper()   #把字母都变成大写
# f.close()
#
# f = open("stus.txt",'w',encoding="utf-8")   #w模式打开,文件被清空
# f.write(content)
# f.close()
#
# f = open("stus.txt","a+",encoding="utf-8")
# f.seek(0)
# content = f.read()
# f.seek(0)
# f.truncate()    #删除文件的内容,从指针的位置开始删除
# # print(content.split())
# for stu in content.split():
#     stu = stu.capitalize()   #把首字母大写
#     # f.write(stu)
#     f.write(stu+"\n")

# 2.一行一行处理
import os
f = open("stus.txt",encoding="utf-8")
f2 = open("stus_new.txt","w",encoding="utf-8")

for line in f:
    line = line.capitalize()
    f2.write(line)
f.close()
f2.close()

os.remove("stus.txt")  #删除原文件
os.rename("stus_new.txt","stus.txt")  #把新文件改名成原文件

 

posted @ 2022-03-01 23:25  青青子佩-  阅读(73)  评论(0编辑  收藏  举报