通过一个例子来熟悉文件的基本操作:创建文件,读取文件,修改文件,删除文件,重命名文件,判断文件是否存在

 '''
编写可供查询的员工信息表--学号 姓名 年龄 班级
1. 提供格式化查询接口
2. 允许用户添加或者删除员工信息
'''
import os
employee_dir = 'employee_list'
index=employee_dir+"/index" if(not os.path.exists(employee_dir)):
os.mkdir(employee_dir,777) def add_student(id,name,age,_class):
local_file = employee_dir+"/"+str(id)
if(os.path.isfile(local_file)):
print("id: %s 已经存在,请重新添加" %(id))
else:
f=open(local_file,"w")
f.write(name+"\t"+str(age)+"\t"+_class)
f.close()
f=open(index,"a")
f.write(str(id)+"\t"+name+"\n")
f.close()
print("id=%s添加成功" %id) def select_student(**kwargs):
for key in kwargs.keys():
if(key=='id'):
local_file = employee_dir+"/"+str(kwargs[key])
if(not os.path.isfile(local_file)):
print("不存在id:",kwargs[key])
else:
f=open(local_file,"r")
print(kwargs[key],f.read())
elif(key=='name'):
if(not os.path.isfile(index)):
print("不存在name:",kwargs[key])
else:
i=0
f=open(index,"r")
for line in f.readlines():
id,name = line.strip().split("\t")
if(name == kwargs[key]):
i=i+1
select_student(id=id)
if(i==0):
print("不存在name:",kwargs[key])
else:
print("无效的获取方式,只能通过id和name来获取!") def modify_student(id,name,age,_class):
local_file = employee_dir+"/"+str(id)
if(os.path.isfile(local_file)):
os.remove(local_file)
rm_line(index,id)
add_student(id,name,age,_class)
print("id=%s修改成功" %id)
else:
print("id: %s 不存在,请先添加" %(id)) def delete_student(**kwargs):
for key in kwargs.keys():
if(key=='id'):
local_file = employee_dir+"/"+str(kwargs[key])
if(not os.path.isfile(local_file)):
print("不存在id:",kwargs[key],",无法删除")
else:
os.remove(local_file)
rm_line(index,kwargs[key])
print("删除id=%s成功" %kwargs[key])
elif(key=='name'):
if(not os.path.isfile(index)):
print("不存在name:",kwargs[key],",无法删除")
else:
i=0
f=open(index,"r")
for line in f.readlines():
id,name = line.strip().split("\t")
if(name == kwargs[key]):
i=i+1
delete_student(id=id)
if(i==0):
print("不存在name:",kwargs[key],",无法删除")
else:
print("无效的删除方式,只能通过id和name来删除!") def rm_line(file,id):
if(not os.path.isfile(file)):
print("不存在文件:",file)
else:
f= open(file,"r")
of = open(file+".tmp","w")
for line in f.readlines():
localid,localname = line.strip().split("\t")
if(str(id)==localid):
pass
else:
of.write(line,)
f.close()
of.close()
if(os.path.isfile(file+".tmpt")): os.remove(file+".tmpt")
os.rename(file,file+".tmpt")
os.rename(file+".tmp",file)

Python进阶篇:文件系统的操作的更多相关文章

  1. python进阶篇

    python进阶篇 import 导入模块 sys.path:获取指定模块搜索路径的字符串集合,可以将写好的模块放在得到的某个路径下,就可以在程序中import时正确找到. ​ import sys ...

  2. Python 进阶篇

    作者:武沛齐 出处:http://www.cnblogs.com/wupeiqi/articles/5246483.html Model 到目前为止,当我们的程序涉及到数据库相关操作时,我们一般都会这 ...

  3. Python进阶篇四:Python文件和流

    摘要: Python对于文件和流的操作与其他编程语言基本差不多,甚至语句上比其他语言更为简洁.文件和流函数针对的对象除了这两者之外还有,类文件(file-like),即python中只支持读却不支持写 ...

  4. python基础篇 08 文件操作

    本节主要内容:1. 初识⽂件操作2. 只读(r, rb)3. 只写(w, wb)4. 追加(a, ab)5. r+读写6. w+写读7. a+写读(追加写读)8. 其他操作⽅法9. ⽂件的修改以及另⼀ ...

  5. python 进阶篇 迭代器和生成器深入理解

    列表/元组/字典/集合都是容器.对于容器,可以很直观地想象成多个元素在一起的单元:而不同容器的区别,正是在于内部数据结构的实现方法. 所有的容器都是可迭代的(iterable).另外字符串也可以被迭代 ...

  6. Python进阶学习_连接操作Redis数据库

    安装导入第三方模块Redis pip3 install redis import redis 操作String类型 """ redis 基本命令 String set(n ...

  7. go语言之进阶篇文件常用操作接口介绍和使用

    一.文件常用操作接口介绍 1.创建文件 法1: 推荐用法 func Create(name string) (file *File, err Error) 根据提供的文件名创建新的文件,返回一个文件对 ...

  8. python 进阶篇 函数装饰器和类装饰器

    函数装饰器 简单装饰器 def my_decorator(func): def wrapper(): print('wrapper of decorator') func() return wrapp ...

  9. python 进阶篇 python 的值传递

    值传递和引用传递 值传递,通常就是拷贝参数的值,然后传递给函数里的新变量,这样,原变量和新变量之间互相独立,互不影响. 引用传递,通常是指把参数的引用传给新的变量,这样,原变量和新变量就会指向同一块内 ...

随机推荐

  1. linux查看及设置别名,权限,生成ssh秘钥

    1.alias :查看系统中所有的命令别名 2.设定别名 alias 别名='原命令' 3.删除别名 unalias 别名 4.使别名永久生效    vi  ~/.bashrc  写入这个文件中即可永 ...

  2. mysql 时间戳

    需求:记录表中每条记录创建时间和最新修改时间 一.界面操作 工具:mysql-front 右键添加字段createTime和updateTime,字段类型为timestamp 完成,在表中添加一条新纪 ...

  3. base64 与字符串互转

    #region 将Base64编码的文本转换成普通文本 /// <summary> /// 将Base64编码的文本转换成普通文本 /// </summary> /// < ...

  4. 002_IO磁盘深入理解

    一.如何测试云硬盘 https://www.ustack.com/blog/how-benchmark-ebs/#fio

  5. Android图片异步加载

    原:http://www.cnblogs.com/angeldevil/archive/2012/09/16/2687174.html 相关:https://github.com/nostra13/A ...

  6. CCScale9Sprite 的 setContentSize setPreferredSize 区别

    CCScale9Sprite 设置图片大小方式: updateButtonSpriteMark->setContentSize(size);//设置图片的原始大小设置节点的未转换大小.无论节点被 ...

  7. 打造 Laravel 优美架构 谈可维护性与弹性设计

    转载:https://juejin.im/post/5be4475c518825170559c044

  8. 数据库-mysql数据类型

    MySQL 数据类型 MySQL中定义数据字段的类型对你数据库的优化是非常重要的. MySQL支持多种类型,大致可以分为三类:数值.日期/时间和字符串(字符)类型. 数值类型 MySQL支持所有标准S ...

  9. python去除html空格

    如下面的 <td> 柳暗花溟</td> html里面的空格&nbsp,想直接用strip()函数去除是不可能的,必须显式的去掉\xa0 例如以上的就可以这样的方式去除空 ...

  10. Python_oldboy_自动化运维之路(三)

    本节内容 列表,元组,字典 字符串操作 copy的用法 文件操作 1.列表,元组,字典 [列表] 1.定义列表 names = ['Alex',"Tenglan",'Eric'] ...