file 文件的处理 文件的类型:txt html (xml excel)—第三方库处理 1.打开文件 open(mode=‘r’) #mode 常用的有: r w a r+ w+ a+ rb wb ab rb+ wb+ ab+ (b是二进制文件) file=open(“do_file”,“r”) file.write(“88888”) res=file.read() #进行一次读取后光标就到了末尾 file.write(“66666”) print(res) 2.读/写/追加 1)file文件默认打开时是r 只读模式,如果要写入会报错:iio.UnsupportedOperation: not writable 2)r+ 方法注意先读/先写的不同 读写是跟着光标位置走 先写是从头覆盖,读光标之后的内容 3)中文的写入:要注意编码格式 utf-8(不能跟read一起用,光标问题) gbk gb2312等 4)w 只写,硬要读会报错 5)不管 w w+ 如果文件存在就清空再写,如果没有就创建然后写入 6)a 追加 a+ 推荐 如果文件存在就追加写,不存在就新建写入 7)换行写入 \n 转义字符 3.读/写操作 file=open(“do_file”,‘r+’) 1)全部读取 res=file.read() 2)按行读取 res=file.readline() res_1=file.readline() 3)读取多行 res=file.readlines() #—返回的是一个列表 4)写多行 res=file.writelines([“111111\n”,“2222222”]) print(res) print(res_1) 4.文件的新建/删除: 1)新建:open() file=open(“aa.py”,“w+”) file.close() 2)删除 import os os.remove(“aa.py”) 5.文件的拷贝/文件内容的拷贝 import shutil file_path=r"D:\python_auto_testing\class_for_python\do_file" new_path=r"D:\python_auto_testing\class_for_python\do_1_file" path=shutil.copy(file_path,new_path) print(path) #new_path文件不存在,新建并拷贝file_path文件的内容 拓展 decode 和 incode 编码关系 光标的移动,可以指定读取的行数吗