写入文件

mac2022-06-30  33

""" IO操作 文件操作: 文件的分类: 广义: 狭义: 文件的作用: 数据持久化 传统文件的操作: 1.打开文件 2.读写操作 3.关闭文件 写: 课下查阅: 绝对路径 相对路径 将内存中的数据->文件 绝对路径: E:\offcn\授课班级\9.基地系统0902班\Day14代码\demo01_知识回顾.py 相对路径: demo02.py f = open('demo02.py','打开方式','文件编码方式') f.write('字符串内容') 读: 从文件中读取出来->内存 read(n) 读取指定长度n,如果不指定长度,默认读取所有 readline() 只读取一行 readines() 读取所有行,存储到列表中 # 循环录入一首诗,存储到文件中 """ # 将一首诗写入到文件中 def poem_write(): # 打开文件 f = open('文件名加后缀.txt,'a',encoding='utf-8') for i in range(1,5): s = input(f'请输入第{i}句') # 将字符串s的内容写入到文件f中 f.write(s+'\n') else: # 关闭文件 f.close() # poem_write() def poem_read(): f = open('文件名加后缀.txt', 'r', encoding='utf-8') # s = f.read(5)#读5个 # s = f.readline()#读一行 s = f.readlines()#全部读一遍 print(s) f.close()#关闭 poem_read() """ 完成某个文件的复制(读写),新文件名的处理 123.txt.py 123.txt-副本.py 对图片复制的注意事项 打开方式: rb 写入方式: wb 不需要指定编码格式 """

 

def copyfile(oldfile): #读取旧文件内容 with open(oldfile,'r',encoding='utf-8') as f: s=f.read() # 新文件名 # index = oldfile.rfind('.') # oldname = oldfile[:index] # newname = oldname+'-副本' # # 包含.的后缀 # suffix = oldfile[index:] # newname += suffix # newname = oldfile[:oldfile.rfind('.')] + '-副本' + oldfile[oldfile.rfind('.'):] # t = oldfile.rpartition('.') newname = t[0]+'-副本'+t[1]+t[2] # print(newname) # 打开新文件 with open(newname,'w',encoding='utf-8') as f1: # 写入操作 f1.write(s) # copyfile('poem.txt') # 图片复制 def copyfile1(oldfile): # 读取旧文件内容 with open(oldfile,'rb') as f: s = f.read() t = oldfile.rpartition('.') newname = t[0]+'-副本'+t[1]+t[2] # print(newname) # 打开新文件 with open(newname,'wb') as f1: # 写入操作 f1.write(s) copyfile1('bird1.png')

 

最新回复(0)