(二)文件的读写原理(读取磁盘文件中的内容)修改py文件的编码格式:在程序第一行写 #encoding=gbk 修改为gbk编码格式
file=open("a.txt","r") #"r"表示read
print(file.readlines()) #readlines()会将文本文件中的内容读出且以列表形式展示
file.close()
(三)常用的文件打开方式
source_file=open("logo.png",rb) #源文件以读的二进制方式读取
target_file=open("copy.png",wb) #目标文件以写的二进制文件写,目标文件是copy.png
target_file.write(source_file.read())
source_file.close()
target_file.close()
(四)文件对象的常用方法
(五)with语句(上下文管理器)tell()方法指针位置从0开始算
flush()方法之后仍然可以向文件写入内容(因为没有关闭文件),但close()方法之后不行
with open("c.txt","r") as file: #相当于file=open("c.txt","r")
print(file.read()) #不用再写file.close(),因为离开with语句块时自动关闭文件资源
#with语句实现文件的复制
with open("a.png","rb") as source_file:
with open("b.png","wb") as target_file:
target_file.write(source_file.read())
(六)目录操作
import os
os.system("notepad.exe") #打开记事本,也可在WIN中输入notepad
os.system("calc.exe") #打开计算器,也可在WIN中输入
#os模块也可直接调用可执行文件
该部分函数和ubuntu系统的终端命令又相似
该部分一般用在办公自动化
import os
print(os.getcwd())
lst=os.listdir("../chap15") #listdir()函数返回列表,".."表示上一级目录
print(lst)
os.mkdir(newdir) #创建目录
os.makedirs("/a/b/c") #创建多级目录
os.rmdir(newdir) #删除目录
os.removedirs("a/b/c") #删除多级目录



