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

 '''
编写可供查询的员工信息表--学号 姓名 年龄 班级
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. win7.wifi热点

    使用本地连接上网,将网卡设为wifi热点 cmd 管理员身份运行 netsh wlan set hostednetwork mode=allow ssid=4Gtest key=12345678 网络 ...

  2. Django 创建第一个Project — Django学习(二)

    检查django If Django is installed, you should see the version of your installation. If it isn’t, you’l ...

  3. 命名实体识别(NER)

    一.任务 Named Entity Recognition,简称NER.主要用于提取时间.地点.人物.组织机构名. 二.应用 知识图谱.情感分析.机器翻译.对话问答系统都有应用.比如,需要利用命名实体 ...

  4. 当遇到not a dynamic executable时怎么做

    当我使用ldd查找Drcom所缺少的32为库的时候提示not a dynamic executable 最后网上找到答案 来自http://forum.ubuntu.org.cn/viewtopic. ...

  5. Linux内核跟踪之ring buffer的实现【转】

      转自:http://blog.chinaunix.net/uid-20543183-id-1930845.html ---------------------------------------- ...

  6. 众签demo

    众签demo using System; using System.Collections.Generic; using System.Linq; using System.Text; using S ...

  7. scala可变长度参数(转)

    可变长度参数 Scala 允许你指明函数的最后一个参数可以是重复的.这可以允许客户向函数传入可变长度参数列表.想要标注一个重复参数,在参数的类型之后放一个星号.例如: scala> def ec ...

  8. java基础26 线程的通讯;wait()、notify()、notifyAll()等方法

    线程的通讯:一个线程完成了自己的任务时,要通知另一个线程去完成另一个任务 1.1.方法 wait():等待.如果线程执行到了wait()方法,那么该线程会进入等待状态,等待状态下的线程必须要被其他线程 ...

  9. P2448 无尽的生命

    Description 小 a有一个长度无限长的序列 p = (1, 2, 3, 4 --),初始时 pi = i 给出 m 个操作,每次交换两个位置的数 询问最后序列逆序对的个数 Solution ...

  10. Django基础 - 修改默认SQLite3数据库连接为MySQL

    Django数据库连接默认为SQLite3,打开setting.py可以看到数据库部分的配置如下: DATABASES = { 'default': { 'ENGINE': 'django.db.ba ...