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

python基础学习(6)—使用Python处理文件

2017-12-26 09:28 543 查看
Python提供了os、os.path等模块处理文件,os提供了对系统环境、文件、目录等操作的权限

1.文件创建

#coding=utf-8
#创建文件
context = "hello world"

f = open("context.txt","w")
f.write(context)
f.close()


file:被打开的文件名称,如果file不存在,open()将创建名为name的文件,然后打开该文件

mode:文件被打开的模式

r :只读    r+:读写  

w:只写  w+:读写 (删除原文件内容,从新写入)

a:写入   a+:读写(在文件末尾追加新内容)

b:以二进制形式打开   注意:对于读片,视频必须使用b

u:支持所有的换行符

buffering:设置缓存模式,0为不缓存,1为缓冲,>1为缓冲区大小,以字节为单位

2.文件的读取

1)按行读取readline()

#读取文件
f = open('context.txt')
while True:
line = f.readline()
if line:
print(line)
else:
break
f.close()

报错:1.io.UnsupportedOperation:not readable python
处理:1.将文件写入模式改为读写模式;2.写入文件后,需要关闭文件后,在进行读取

2)多行读取readlines()

#多行读取
f = open("context.txt")
lines = f.readlines()
for line in lines: #一次读取多行
print(line)
f.close()
3)一次性读取read()
#一次性读取
f = open("context.txt")
context = f.read(5) #读取文件
print(context)
print(f.tell()) #返回文件当前指针位置
context = f.read(5) #继续读取文件
print(context)
print(f.tell()) #返回文件当前指针位置
f.close()3.文件写入
#coding=utf-8
#文件的写入
f = open('test_01.txt',"w+")
test = ["hello world\n" , "hello world\n"]
f.writelines(test)
f.close()

#在文件中追加新的内容
f = open('test_01.txt','a+')
test = ('liyan')
f.writelines(test)
f.close()





4.文件的删除

***删除文件时,必须先判断文件是否存在,如果存在文件将被删除,如果不存在,操作将不实现

#coding=utf-8
#删除文件
import os
open("test_01","w")
if os.path.exists("test_01"):
os.remove("test_01")
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐