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

python基础(4)--文件对象,指针,os,os.path模块

2016-03-24 10:13 489 查看
In [105]:f1 = open('/tmp/passwd','r+') 读写方式打开
In [106]: f1.next() 读一行,next陆续往下读,不会移动行指标
Out[106]: 'root:x:0:0:root:/root:/bin/bash\n'
In [107]: f1.seek(0,2) 从文件末尾行(2)偏移位置0(0),f1.seek(0)回到开始处
In [109]: f1.tell() 查看文件位置(字节)
Out[109]: 1576
In [110]: f1.write('new line.\n') 添加一行
In [112]: f1.readline() 读取一行,移动行指标
Out[112]: ''
In [129]: f1.closed 判断是否关闭
Out[129]: False 否
In [132]: f1.close() 关闭
In [133]: f1.closed
Out[133]: True 是
实例:将1到10的幂运算结果写入到test.txt
f1 = open('/tmp/test.txt','w+')
for line in ( i**2 for i in range(1,11) ):
f1.write(str(line) + '\n')
f1.flush()
f1.close()
将目录/ext下文件列表结果写入到文件test1.txt
f1 = open('/tmp/test1.txt','w+')
import os
l1 = os.listdir('/etc') #列出目录下的文件
f1.writelines(l1) #将字符串列表内容写入到文件,不能写入整数类型的数据。
f1.flush()
f1.close()
注意:如果要给每个文件加入换行符\n,可以如下定义:
f3=open('/tmp/test3.txt','w+')
l2 = [i+'\n' for i in os.listdir('/etc')]
f3.writelines(l2)

实例:输入内容到文件
#!/usr/local/bin/python27
#
import os
import os.path #加载模块
filename='/tmp/test.txt'
if os.path.isfile(filename): #判断是否有文件filename
f1 = open(filename,'a+') #追加打开模式
while True:
line = raw_input('Enter something>>') #交互输入模式
if line == 'q' or line == 'quit':
break
f1.write(line+'\n')
f1.close()
实例:指针
指针:打开一个文件,迭代print以后,指针会到最后,第二次打印的时候需要将指针恢复到最开始
In [2]: f1 = open('/etc/passwd','r')
In [3]: for line in f1:
...: print line,
...: print '==================='
...:
root:x:0:0:root:/root:/bin/bash
===================
bin:x:1:1:bin:/bin:/sbin/nologin
===================
daemon:x:2:2:daemon:/sbin:/sbin/nologin
In [5]: f1.tell()
Out[5]: 1576
In [6]: f1.seek(0) #需要将指针恢复到最开始
In [7]: for line in f1:
print line,
print '==================='
...:
root:x:0:0:root:/root:/bin/bash
===================
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python