Python的文件操作

Python的文件操作:

打开文件;open函数

open的方式有三种

1,r(read-only)也是python中默认的文件打开模式

2,w(write-only)只写模式,比较危险,会覆盖当前文件内容

3,a(append)追加模式,对文件追加内容

 

读取文件:

读取的方式有三种

 read() 每次读取整个文件内容,并且赋值到一个变量,如果文件大于内存。是不能实现这种方式的

readline()

readlines()

后两者非常相似,唯一的区别是readines是一次读取整个文件,将文件内容分析称一个行的列表,该列表可以用python的for..in..结构进行处理。

而readline每次只读一行,比readlines慢的多,仅当没有足够内存可以一次性读取整个文件时,才会使用.readline()

最基本的打开文件脚本:

#!/usr/bin/env python
a =open('/etc/passwd')    以读的方式打开/etc/passwd文件
b =a.read() 读取整个文件内容,并且赋值到变量b
a.close() 关闭文件
print(b) 打印变量b

 

通过for _ in range()语句,来读指定的行

#!/usr/bin/env python
file = open('/etc/passwd','r')
for a in range(4):    设置一个for循环,循环次数=4
    print(file.readline()) 一行一行读取,读取4次(4行)
file.close  关闭文件

以列表的方式来读文件

#!/usr/bin/env python 
file = open('/etc/passwd','r')
list = file.readlines() 把readlines的结果写入列表list
file.close 关闭文件
a=list[0:3] 切割列表a,只保留前3个index
print(a)

 

对文件执行写操作:

 write,writelines

write(string)

write是直接写入字符串

#!/usr/bin/env python
file=open('test.txt','w') --如果文件已经存在,会覆盖原先内容
file.write('this is an test file,\nAnd Alben is very hard study\n')
file.close()

writelines(list)

writelines是可以把列表写入文件的

#!/usr/bin/env python
a=["apple\n"]
b=["orange\n"]
c=["banana\n"]
file=open('lines.txt','w')
file.writelines(a)
file.writelines(b)
file.writelines(c)
file.close

需要注意的是,把列表写入文件的时候,writelines不支持换行,所以必须在列表中写入换行符

#!/usr/bin/env python
file=open("userdb","a+")
file.write("hello\n")

posted @ 2017-05-03 15:33  alben-xue  阅读(199)  评论(0编辑  收藏  举报