python 文件管理系统
2018-01-18 21:39
411 查看
文件管理
# 1. open 内置函数打开文件, 返回值是一个文件对象 ; 默认文件打开方式为只读 'r'; f = open("/home/kiosk/hello") print type(f) # 2. 读取文件内容 f.read() # 3. 关闭文件 f.close()
文件操作的其他模式
理解模式不同的三个点文件不存在,是否报错;
文件是否只读,只写还是读写;
文件清空原有内容还是追加文本信息;
范例
‘w’模式:
当以写的方式打开文件,先清空文件的所有内容;
只能写入文件,不能读取文件内容;
f = open("/home/kiosk/hello", 'w') # f.read() f.write("westos") f.close()
r+ w+ a a+** 如果读取的文件是一个非文本文件,在原有模式上加b; eg: 'rb', 'rb+', 'wb+', 'ab', 'ab+';
seek
f = open("/home/kiosk/hello", 'a+') # f.write("hello") f.read() # seek 需要传两个值; # 第一个参数: 偏移量 ; 偏移量 >0 , 代表向右移动的字符; 反之,向左移动的字符 ; # 第二个参数 : 0 : 文件开头; 1 : 代表当前位置; 2 : 文件末尾 ; f.seek(3, 0) print f.tell() f.read()
读文件
readline方法依次读取文件,仅返回一行文件信息;readlines方法以列表方式返回文件信息; 默认保留换行符;
f = open("/etc/passwd", 'r') # 程序员常用操作: print [i.strip() for i in f.readlines()][:5] f.close()
写文件
write
writeline可以写入多行文本内容;
f = open("/home/kiosk/hello", 'a+') print f.read() f.writelines(["hello\n", "python\n", "java\n"]) # 程序员常用操作: # help(f.writelines) f.seek(0) f.close()
文件对象f是可迭代的?
判断可迭代的两种方式?isinstance(f, Iterable)
for循环
from collections import Iterable f = open("/etc/passwd") print isinstance(f, Iterable) # 文件对象可以 for 循环遍历; for i in f: print i f.close() # for i in f.readlines: # print i
文件内置属性
# 返回 bool 值,判断文件对象的状态; print f.closed # 查看文件的打开模式 print f.mode # 查看文件名 print f.name
with语句
with open("/etc/passwd") as f1: print f1.read() print f1.closed
应用练习
显示文件的所有行,但忽略以#开头的行;
拓展:
处理#不在文件开头的注释;
with open("/tmp/hello") as f: for line in f: if line.strip()[0] != "#": print line,
把/etc/passwd文件中的”root”字符串替换为”westos”, 将更换后的另存为/tmp/passwd文件;
with open("/etc/passwd") as f1: # 遍历文件的每一行内容 ; for line in f1: # 字符串的替换 bline = line.replace("root", "westos") with open("/tmp/passwd", "a+") as f2: # 写入新文件 f2.write(bline)
相关文章推荐
- Python 创建、读取和写入文件以及yield关键字- 千月的python linux 系统管理指南学习笔记(14)
- python(基于列表/将学生管理系统写入本地文件)
- python下学生管理系统:从文件中读取30位学生的信息(含邮箱),并实现简单的增、删、查找、统计(邮箱使用人数)。---附程序哦!
- Python的系统管理_11_ConfigParser读取配置文件
- Python学习之路——Linux基础之文件系统管理
- Python备份文件、文件版本的学生管理系统如何实现(将数据保存在txt文件中)
- 第八章、Linux 磁盘与文件系统管理
- 文件系统管理 之 Fedora Core 4.0 HAL配置即插即用移动存储(USB及1394)的实践
- Linux的磁盘与文件管理系统(1)
- php 登录操作的文件上传管理系统
- 文件系统管理 之 文件和目录访问权限设置
- 系统管理-02 目录和文件管理
- iOS NSFileManager文件系统的管理
- 把asp程序封装成可执行文件(无需IIS web服务器)直接运行的管理系统
- linux 学习之九、Linux 磁盘与文件系统管理(2)
- Linux学习笔记(14)文件系统管理
- Linux磁盘和文件系统管理(一)
- 项目二 任务六:管理Linux系统的文件权限
- 文件系统的管理方法和xfs文件系统备份恢复
- python3.6+django2.0开发一套学员管理系统