- 一、读文件
''' 1.打开文件 2.写数据 3.关闭 w覆盖 a追加 ''' path=r'C:\Users\asus\Desktop\2.txt' a=open(path,'a') a.write('明天考试')#覆盖原文件列表的所有数据,无文件就会自动创建新文件 a.close()
- 二、写文件
''' 文件操作: 1.读 打开文件 读 关闭 2.写 ''' #打开文件 # path=r'C:\Users\asus\Desktop\jxk\实习练习\day2\人机猜拳.py' # a=open(path,'r',encoding='utf-8') #读取全部 # print(a.read()) #读取指定数量的字符 # print(a.read(10)) #一次读取一行 # print(a.readline()) #读取多行,并将每一行的内容添加到列表中 # print(a.readlines()) # a.close() #用二进制打开文件,decode('gbk')是转码 path=r'C:\Users\asus\Desktop\1.txt' b=open(path,'rb') print(b.read().decode('gbk'))
- 三、复制文件
''' 打开a文件夹下的a.txt 读取1.txt的所有数据 在b文件夹下打开并创建一个2.txt 把1读出来的数据写入到2里边 ''' # path=r'C:\Users\asus\Desktop\a\1.txt' # f=open(path,'r') # str=f.read() # path2=r'C:\Users\asus\Desktop\b\2.txt' # f1=open(path2,'w') # f1.write(str) # f.close() # f1.close() #复制除图片外的文件 # path=r'C:\Users\asus\Desktop\a\11.jpg' # f=open(path,'rb') # str=f.read() # path2=r'C:\Users\asus\Desktop\b\22.jpg' # f1=open(path2,'wb') # f1.write(str) # f.close() # f1.close() path=r'C:\Users\asus\Desktop\a\电影.mp4' a=open(path,'rb') str=a.read() path1=r'C:\Users\asus\Desktop\b\电影.mp4' b=open(path1,'wb') b.write(str) a.close() b.close()