您的位置:首页 > 编程语言 > Python开发

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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: