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

 '''
编写可供查询的员工信息表--学号 姓名 年龄 班级
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. python初步学习-python 模块之 json

    json 模块 JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写.一般API返回的数据大多是 JSON.XML,如果返回JSON的话,将获取 ...

  2. Python练习-time模块

    明天的明天的明天,雾草! # 编辑者:闫龙 #显示当前时间三天后是星期几? import time t = time.time()+((24*3600)*3) tl = time.localtime( ...

  3. win10安装

    1.启动盘制作 首先我们需要登陆“微软中国下载中心”,从中下载一款名为“MediaCreationTool”的工具,利用该工具可以制作Win10安装U盘.直接通过以下地址快速进入“Windows下载中 ...

  4. C# FileStream进行FTP服务上传文件和下载文件

    定义FileStream类的操作类:操作类名: FtpUpDown 上传文件 /// <summary> /// 上传文件 /// </summary> /// <par ...

  5. docker stack 部署 rabbitmq 容器

    =============================================== 2018/5/13_第1次修改                       ccb_warlock == ...

  6. 线性表应用--Josephus问题的解法(Python 版)

    线性表应用 --Josephus问题的解法(Python 版) Josephus问题描述:假设有n个人围坐一圈,现在要求从第k个人开始报数,报到第m个数的人退出.然后从下一个人开始继续报数并按照相同的 ...

  7. dragstart drag dragend dragenter dragover dragleave drop

    dragstart drag dragend dragenter dragover dragleave drop   前端框架层出不穷,网页上的效果越来越绚丽,制作绚丽的效果的成本越来越低,其中有种拖 ...

  8. ASP .Net Core系统部署到Ubuntu 16.04 具体方案

    .Net Core 部署到Ubuntu 16.04 中的步骤 1.安装工具 1.apache 2..Net Core(dotnet-sdk-2.0) 3.Supervisor(进程管理工具,目的是服务 ...

  9. Oracle JDeveloper 10g 卡顿、花屏的解决方法

    1.JDeveloper 10g花屏的解决办法: 在Win7或WinXP环境下,JDeveloper10g可能产生花屏现象,给开发者造成困扰,解决方法如下: 打开{JDEV_HOME}\jdev\bi ...

  10. java 二叉树遍历

    package com.lever; import java.util.LinkedList;import java.util.Queue; /** * 二叉树遍历 * @author lckxxy ...