>>> fo = open("/root/a.txt")
>>> fo
<open file '/root/a.txt', mode 'r' at 0x7f5095dec4e0>
>>> fo.read()
'hello davehe\ni am emily\nemily emily\n'
>>> fo.close() >>> fo.read() #对象已关闭,在读取就读不到
Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: I/O operation on closed file
>>> f1 = file("/root/a.txt")
>>> f1.read()
'hello davehe\ni am emily\nemily emily\n'
>>> f1.close()
root@10.1.6.200:~# ls -l new.txt
ls: cannot access new.txt: No such file or directory
>>> fnew = open("/root/new.txt",'w') w参数文件没有则创建
>>> fnew.write('hello \n i am dave')
root@10.1.6.200:~# cat new.txt root@10.1.6.200:~#
>>> fnew.close() root@10.1.6.200:~# cat new.txt
hello i am dave
>>> fnew = open("/root/new.txt","w")
root@10.1.6.200:~# cat new.txt root@10.1.6.200:~#
>>> fnew = open("/root/new.txt",'r+')
>>> fnew.read()
'hello dave'
>>> fnew.write('i am dave')
>>> fnew.close()
root@10.1.6.200:~# cat new.txt
hello davei am dave
>>> fnew = open("/root/new.txt",'r+')
>>> fnew.write('ooo')
>>> fnew.close()
root@10.1.6.200:~# cat new.txt
ooolo davei am dave
>>> for i in open("/root/a.txt"): 用open可以返回迭代类型的变量,可以逐行读取数据
... print i
...
hello davehe i am emily emily emily
>>> f1 = open("/root/a.txt")
>>> f1.readline()
'hello davehe\n'
>>> f1.readline()
'i am emily\n'
>>> f1.readline()
'emily emily\n'
>>> f1.readline() '' >>> f1.readline() '' >>>f1.close()
>>> f1 = open("/root/a.txt")
>>> f1.readlines()
['hello davehe\n', 'i am emily\n', 'emily emily\n']''
>>> f1 = open("/root/a.txt")
>>> f1.next()
'hello davehe\n'
>>> f1.next()
'i am emily\n'
>>> f1.next()
'emily emily\n'
>>> f1.next()
Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
>>> l = ["python\n","python\n","python\n"]
>>> f1 = open('/root/a.txt','a')
>>> f1.writelines(l)
>>> f1.close()
root@10.1.6.200:~# cat a.txt
hello davehe i am emily emily emily python python python
>>> f1 = open('/root/a.txt','r+')
>>> f1.read()
'hello davehe\ni am emily\nemily emily\npython\npython\npython\n'
>>> f1.seek(0,0) 指针指到开头,在读 >>> f1.read()
'hello davehe\ni am emily\nemily emily\npython\npython\npython\n'
>>> f1.read() '' >>> f1.seek(0,0) >>> f1.seek(0,2) 指针指到末尾,在读 >>> f1.read() ''
root@10.1.6.200:~# vim file.py
#!/usr/bin/env python
import re
f1 = open('/root/a.txt')
count = 0
for s in f1.readlines():
li = re.findall("emily",s)
if len(li) > 0:
count = count + len(li)
print "this is have %d emily" % count
f1.close()
root@10.1.6.200:~# cat a.txt
hello davehe i am emily emily emily
root@10.1.6.200:~# python file.py
this is have 3 emily
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有