ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

运算符 文件操作 6

运算符 文件操作 6 运算符算数运算: - * / % ////整除%求余比较运算 !赋值运算 - *a21 b2 a,bb,a#只适合python print(a)#2 print(b)#21逻辑运算and or not当andor和not同时出现的时候最好加上括号不会产生歧义或者不易理解的问题运算顺序先算括号——算not——and——or成员运算in 判断xxx是否在xxx中出现了not in 判断xxx是否不在xxx中出现了文件操作open(文件路径mode,encoding)文件路径1.绝对路径d/test/xxx.txt2.相对路径相对于当前你的程序所在的文件夹../ ——上一层文件夹fopen(sgias.txt,moder,encodingutf-8) print(f.read())#读取所有 linef.readline().strip()#读取一行.strip是去除空格换行 print(line) linef.readline().strip() print(line)最重要的的一种文本读取方式通过循环fopen(sgias.txt,moder,encodingutf-8) for line in f: print(line.strip())r——读w——写a——append 追加写入b——读写的是非文本文件——byteswith ——上下文不需要手动去关闭一个文件w模式下如果文件不存在自动创建一个文件w模式下每一次执行open都会清空掉文件中的内容fopen(sgias.txt,modew,encodingutf-8) f.write(hhhhhhhhhhhhhhh) f.close()#每次操作之后养成好习惯要关闭链接#大多数情况下要把open写循环外面例子将一个列表要求把列表中的每一项内容写入到文件中list[周清,shjsakd,hdk] fopen(sgias.txt,modew,encodingutf-8) for item in list: f.write(item) f.write(\n) f.close()a——追加写fopen(sgias.txt,modea,encodingutf-8) f.write(你好厉害)with——上下文不需要手动去关闭一个文件with open(sgias.txt,moder,encodingutf-8) as f: for line in f: print(line.strip()) #省略了close读取图片#再读写非文本文件的时候要加上b with open(2.jpg,moderb) as f: for line in f: print(line)复制文件#\的作用是将第一行与第二行的代码结合在一起 with open(2.jpg,moderb) as f1, \ open(../实验任务二/3.jpg,modewb) as f2: for item in f1: f2.write(item)文件修改删除文件#删除文件 import os#和操作系统相关的模块引入 with open(人名单.txt,moder,encodingutf-8) as f1,\ open(人名单副本.txt,modew,encodingutf-8) as f2: for line in f1: lineline.strip() if line.startswith(周): lineline.replace(周,张) f2.write(line) f2.write(\n) #删除文件 os.remove(人名单.txt) #重命名 os.rename(人名单副本.txt,人名单.txt)
返回列表