Python入门篇-文件操作
Python入门篇-文件操作
作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。
一.文件IO常用操作
open:打开
read:读取
write:写入
close:关闭
readline:行读取
readlines:多行读取
seek:文件指针操作
tell:指针位置
二.基本操作
1>.打开操作
#!/usr/bin/env python
#_*_coding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
#EMAIL:y1053419035@qq.com """
open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
打开一个文件,返回一个文件(流对象)和文件描述符。打开文件失败,则返回异常。 """ f = open("passwd") #file对象,默认以只读方式打开文件,该文件必须存在,否则会抛出"FileNotFoundError"异常
print(f.read()) #d读取文件
f.close() #关闭文件 #"passwd"文件内容如下:
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
polkitd:x:999:998:User for polkitd:/:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
chrony:x:998:996::/var/lib/chrony:/sbin/nologin
yinzhengjie:x:1000:1002:yinzhengjie:/home/yinzhengjie:/bin/bash
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin
zabbix:x:997:995:Zabbix Monitoring System:/var/lib/zabbix:/sbin/nologin
mysql:x:27:27:MySQL Server:/var/lib/mysql:/bin/bash
python:x:1001:1001::/home/python:/bin/bash
2>.mode模式
描述字符 意义
r 缺省的(即如果没有指定mode模式,则默认以只读方式打开),表示只读打开,如果使用write方法,会抛异常。如果文件不存在,抛出"FileNotFoundError"异常。
w 只写打开,如果文件不存在直接创建,如果文件已经存在,则清空文件内容,如果读取则抛出异常。
x 创建并写入一个新文件,文件不存在,创建文件,并只写方式打开。
a 写入打开,如果文件存在,则追加。文件存在,只写打开,追加内容,文件不存在,则创建后,只写打开,追加内容。
b 二进制模式,字节流,将文件就按照字节理解,与字符编码无关。二进制模式操作时,字节操作使用bytes类型。
t 缺省的文本模式。字符流,将文件的字节按照某种字符编码理解,按照字符操作,open的默认mode就是rt。
+ 读写打开一个文件,给原来只读,只写方式打开提供缺省的读或者写能力。主要为r,w,a,x提供缺省的读写能力,但是文件获取依旧依照按照r,w,a,x字节的特征,+不能单独使用,可以任务它是为前面的模式字符做增强功能的。
#!/usr/bin/env python
#_*_coding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
#EMAIL:y1053419035@qq.com """
文件操作中,最常用的操作就是读和写。
文件访问的模式有两种:文本模式和二进制模式。不同模式下,操作函数不尽相同,表现的结果也不一样。
打开或者要创建文件名。如果不指定路径,默认就是当前路径 """ f = open("passwd") #file对象,默认以只读方式打开文件,该文件必须存在,否则会抛出"FileNotFoundError"异常
print(f.readline()) #d读取文件
f.close() #关闭文件 print("*" * 20 + "我是分割线" + "*" * 20) f = open("passwd","r")
f.write("abc") #这里会抛异常"io.UnsupportedOperation: not writable",因为我们是以只读方式打开,但是我们这里要进行写操作是不被允许的!
f.close()
r模式打开文件
#!/usr/bin/env python
#_*_coding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
#EMAIL:y1053419035@qq.com f = open("a.txt","w") #以只写的方式打开
f.write("") #往打开的文件描述符写入内容为"123"
f.close() #关闭文件 f = open("a.txt","r") #我们可以读出来写入的内容
print(f.read())
f.close() #以上代码执行结果如下:
123
w模式打开不存在的文件
#!/usr/bin/env python
#_*_coding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
#EMAIL:y1053419035@qq.com f = open("a.txt","r") #我们可以读出来写入的内容
print(f.read())
f.close() print("*" * 20 + "我是分割线" +"*" *20) f = open("a.txt","w") #以只写的方式打开,由于文件已经存在,我们再次打开它会将之前该文件的内容全部清空!
f.write("") #我们往清空后的文件写入数据
f.close() #关闭文件 f = open("a.txt","r") #我们可以读出来写入的内容
print(f.read())
f.close() #以上代码执行结果如下:
123
********************我是分割线********************
666
w模式打开已经存在的文件
三.文件指针,指向当前字节位置
mode=r
指针起始在于0
mode=a
指针起始在EOF
tell()
显示指针当前位置
seek(offset[,whence])
移动文件指针位置。offset偏移多少字符(即seek是按照自己偏移的) 文本模式下
whence 0
缺省值,表示从头开始,offset只能正整数
whence 1
表示从当前位置,offset只接受0,相当于原地不动,没有什么用。
whence 2
表示从EOF开始,offset只接受0,相当于移动文件指针到EOF。 二进制模式下
whence 0
缺省值,表示从头开始,offset只能正整数
whence 1
表示当前位置,offset可正可负
whence 2
表示从EOF开始,offset可正可负
二进制模式下支持任意起点的偏移,从头,从尾,从中间位置开始。向后seek可以超界,但是向前seek的时候,不能超界,否则抛异常。
#!/usr/bin/env python
#_*_coding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
#EMAIL:y1053419035@qq.com f = open("a.txt","r+")
print("当前文件读取位置:{}".format(f.tell())) #起始位置,因为我们还没有开始读取
print("*" * 20 + "开始读取文件" + "*" * 20)
print(f.read()) #我们将内容全部读取出来
print("*" * 20 + "文件读取完毕" + "*" * 20)
print("当前文件读取位置:{}".format(f.tell())) #EOF,读取到文件末尾的指针位置
f.seek(0) #回到起始位置
print("当前文件读取位置:{}".format(f.tell())) #查看当前文件指针位置
f.close() #以上代码执行结果如下:
当前文件读取位置:0
********************开始读取文件********************
666
********************文件读取完毕********************
当前文件读取位置:3
当前文件读取位置:0
文本方式打开
#!/usr/bin/env python
#_*_coding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
#EMAIL:y1053419035@qq.com f = open("a.txt","rb+")
print("当前文件读取位置:{}".format(f.tell())) #起始位置,因为我们还没有开始读取
print("*" * 20 + "开始读取文件" + "*" * 20)
print(f.read()) #我们将内容全部读取出来
print("*" * 20 + "文件读取完毕" + "*" * 20)
print("当前文件读取位置:{}".format(f.tell())) #EOF,读取到文件末尾的指针位置
f.write(b"abcdef") #由于我们把之前的内容都读取出来啦,指针知道了文件末尾,此时我们在写入数据,其实在做追加写操作
f.seek(0) #回到起始位置
print("当前文件读取位置:{}".format(f.tell()))
f.seek(2,1) #从当前指针开始,向后移动2个字符
print("当前文件读取位置:{}".format(f.tell()))
f.seek(2,2) #从EOF开始,向后移动2个字符
print("当前文件读取位置:{}".format(f.tell()))
f.seek(0) #回到起始位置
print("当前文件读取位置:{}".format(f.tell()))
f.seek(-2,2) #从EOF开始,向前移动2个字符
print("当前文件读取位置:{}".format(f.tell())) #查看当前文件指针位置
print("*" * 20 + "开始读取文件" + "*" * 20)
print(f.read()) #我们将内容全部读取出来
print("*" * 20 + "文件读取完毕" + "*" * 20)
print("当前文件读取位置:{}".format(f.tell())) #查看当前文件指针位置
f.seek(-20,2) #向前移动20个字符,但是如果向前移动的偏移量没有20个字符的话,就会抛出"OSError"异常
f.close() #以上代码执行结果如下:
当前文件读取位置:0
********************开始读取文件********************
b'abcdefghijklmnopqrstuvwxyz'
********************文件读取完毕********************
当前文件读取位置:26
当前文件读取位置:0
当前文件读取位置:2
当前文件读取位置:34
当前文件读取位置:0
当前文件读取位置:30
********************开始读取文件********************
b'ef'
********************文件读取完毕********************
当前文件读取位置:32
二进制方式打开
四.buffering缓冲区
buffering的分为4类
buffering = -1
-1表示使用缺省值大小的buffer。如果是二进制模式,使用io.DEFAULT_BUFFER_SIZE值,默认是4096或者8192。如果是文本模式,如果是终端设备,是行缓存方式,如果不是,则使用二进制模式的策略。
文本模式(t)和二进制模式(b),都是io.DEFAULT_BUFFER_SIZE
buffering = 0
0只在二进制模式(b)使用,表示环比缓冲区(buffer).文本模式(t)不支持。
buffering = 1
1只在文本模式使用,表示使用行缓冲。意思就是见到换行符(t)就flush,但"io.DEFAULT_BUFFER_SIZE"依旧时缓冲上线。
buffering > 1
大于1用于指定buffer的大小。
二进制模式(b)表示行缓冲大小。缓冲区的值可以超过io.DEFALUT_BUFFER_SIZE,直到设定的值超出后才把缓冲区flush。
文本模式(t)表示io.DEFAULT_BUFFER_SIZE(即默认值大小),flush完后把当前字符串也写入磁盘。 buffering看起来很麻烦,一般来说,只需要记得:
1>.文本模式,一般都用默认缓冲区大小。
2>.二进制模式,是一个个字节的操作,可以指定buiffer的大小
3>.一般来说,默认缓冲区大小是个比较好的选择,除非明确知道,否则不调整它
4>.一般编程中,明确知道需要写磁盘了,都会手动调用一次flush,而不是等到自动flush或者close的时候。 buffer缓冲区
缓冲区一个内存空间,一般来说是一个FIFO队列,到缓冲区满了或者达到阈值,数据才会flush到磁盘。
flush()将缓冲区数据写入磁盘。
clouse关闭前会调用flush()。
io.DEFAULT_BUFFER_SIZE缺省缓冲区大小,字节。
#!/usr/bin/env python
#_*_coding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
#EMAIL:y1053419035@qq.com import io f = open("a.txt","w+b")
print(io.DEFAULT_BUFFER_SIZE) f.write("https://www.cnblogs.com/yinzhengjie".encode()) f.seek(0) f.write("www.baidu.com".encode()) f.flush() f.close() f = open('a.txt',"w+b",4)
f.write(b"yin")
f.write(b"zhengjie")
f.close()
二进制模式
#!/usr/bin/env python
#_*_coding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
#EMAIL:y1053419035@qq.com import io f = open("a.txt","w",1) #buffering=1,使用行缓冲 f.write("yin")
f.write("zhengjie" * 6)
f.write("\n")
f.write("Hello\nPython")
f.close() f = open("a.txt","w+",15) #buffering>1使用指定大小的缓冲区
f.write("yin")
f.write("zhengjie")
f.write("HELLO\n")
f.write("\nPython")
f.write("a" * (io.DEFAULT_BUFFER_SIZE - 20)) #设置大于1没什么用
f.write("https://www.cnblogs.com/yinzhengjie")
f.close()
文本模式
#!/usr/bin/env python
#_*_coding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
#EMAIL:y1053419035@qq.com f = open("a.txt","wb+",0) #buffering = 0这是一种特殊的二进制模式,不需要内存的buffer,可以看做是一个FIFO的文件。
f.write(b"y")
f.write(b"z")
f.write(b"j")
f.write(b"yinzhengjie" * 6)
f.write(b"\n")
f.write(b"Hello\nPython")
f.close()
buffering=0案例
五.编码(Encoding),仅文本模式使用
#!/usr/bin/env python
#_*_coding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
#EMAIL:y1053419035@qq.com """
None表示使用缺省值编码,依赖操作系统,Windows,linux下测试代码如下所示。如果要显示指定的话我们可以用"encoding"关键词进行传参
windows下缺省GBK(0xB0A1),Linux下缺省UTF-8(0xE5 95 8A)
""" f = open("a.txt","w") f.write("中国") f.close()
六.errors
什么样的编码错误将被捕获。
None和strict表示有编码错误将抛出ValueError异常;ignore表示忽略。
七.newline
文本模式中,换行的转换。可以为None,空串,"\r","\n","\r\n"
读时:
None表示'\r','\n','\r\n'都被转换为'\n';表示不会自动转换通过换行符;其他合法字符表示换行符就是指定字符,就会按照指定字符分行。
写时:
None表示'\n'都会被替换为系统缺省行分隔符os.linesep;'\n'或者''表示'\n'不替换,其他合法字符表示'\n'会被替换为指定的字符。
#!/usr/bin/env python
#_*_coding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
#EMAIL:y1053419035@qq.com f = open("a.txt","w") f.write("https://www.cnblogs.com/yinzhengjie\rPython\nhttps://www.cnblogs.com/yinzhengjie\r\nPython3.6") f.close() newlines = [None,'','\n','\r\n']
for line in newlines:
f = open("a.txt",'r+',newline = line) #缺省值替换所有的换行符
print(f.readlines())
f.close() #以上代码执行结果如下:
['https://www.cnblogs.com/yinzhengjie\n', 'Python\n', 'https://www.cnblogs.com/yinzhengjie\n', '\n', 'Python3.6']
['https://www.cnblogs.com/yinzhengjie\r', 'Python\r\n', 'https://www.cnblogs.com/yinzhengjie\r', '\r\n', 'Python3.6']
['https://www.cnblogs.com/yinzhengjie\rPython\r\n', 'https://www.cnblogs.com/yinzhengjie\r\r\n', 'Python3.6']
['https://www.cnblogs.com/yinzhengjie\rPython\r\n', 'https://www.cnblogs.com/yinzhengjie\r\r\n', 'Python3.6']
newline案例
八.closefd
关闭文件描述符,True表示关闭它。False会在文件关闭后保持这个描述符。fileobj.fileno()查看。
九.read
#!/usr/bin/env python
#_*_coding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
#EMAIL:y1053419035@qq.com """
read(size=-1)
size表示读取的多少个字符或字节;负数或者None表示读取到EOF
""" f = open("c.txt","r+",10) #注意,我们传入的第三个参数不能为0,否则会报错"ValueError: can't have unbuffered text I/O"
f.write("https://www.cnblogs.com/yinzhengjie")
f.write("\n")
f.write("尹正杰到此一游!")
f.seek(0)
print(f.read(39))
f.close() f = open("c.txt","rb+")
print(f.read(39)) #注意这里读取的是字节,一个常见的汉字UTF-8字符编码一般对应的是3个字节
print(f.read(1))
f.close() #以上代码输出结果如下:
https://www.cnblogs.com/yinzhengjie
尹正杰
b'https://www.cnblogs.com/yinzhengjie\r\n\xd2\xfc'
b'\xd5'
十.行读取
#!/usr/bin/env python
#_*_coding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
#EMAIL:y1053419035@qq.com """
readline(size = -1)
一行行读取文件内容,size设置一次能够读取行内几个字符或字节。 readlines(hint = -1)
读取所有行的列表,指定hint则返回指定的行数。
""" f = open("a.txt") #返回可迭代对象 for line in f:
print(line) f.close()
十一.write
#!/usr/bin/env python
#_*_coding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
#EMAIL:y1053419035@qq.com """
write(s)
把字符串"s"写入到文件中并返回字符串的个数 writelines(lines)
将字符串列表写入文件。
""" f = open("a.txt","w+") lines = ['Jason',"2019\n","Yinzhengjie"] f.writelines(lines) f.seek(0) print(f.read()) f.close() #以上代码输出结果如下:
Jason2019
Yinzhengjie
十二.close
close:
flush并关闭文件对象。
文件已经关闭,再次关闭没有任何小伙 其他:
seekable()是否可seek
readable()是否可读
writeable()是否可写
closed是否已经关闭
十三.上下文管理
1>.问题的引出
#!/usr/bin/env python
#_*_coding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
#EMAIL:y1053419035@qq.com """
我们可以使用lsof和ulimit查看所有的限制。其中open files就是打开文件数的限制,默认是1024.
对于类似于文件对象的IO对象,一般来说都需要你不使用的时候关闭,注销,以释放资源。
IO被打开的时候,会获得一个文件描述符。计算机资源是有限的,所以操作系统都会做限制。就是为了保护计算机的资源不要被完全耗尽,计算资源是共享的,不是独占的。
一般情况下,除非特别明确的知道资源情况,否则不要提高资源的限制来解决问题。
""""
res = [] for _ in range(2000): #我们要循环2000次,但是在Linux你如果没有做调优的话,就会有"Too many open files"的相关报错
res.append(open("a.txt"))
2>.解决方案一(异常处理)
#!/usr/bin/env python
#_*_coding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
#EMAIL:y1053419035@qq.com f = open("a.txt") try:
f.write("Jason Yin") #文件只读,写入失败
finally:
f.close() #使用finally可以保证打开的文件可以被关闭
3>.解决方案二(上下文管理)
#!/usr/bin/env python
#_*_coding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
#EMAIL:y1053419035@qq.com """
上下文管理:
一种特殊的语法,交给解释器去释放文件。
1>.使用with ... as关键字;
2>.上下文管理的语句块并不会开启新的作用域;
3>.with语句块执行完的时候,会自动关闭文件对象;
""" with open("a.txt","w") as f:
f.write("Jason Yin") print(f.closed) #测试f是否关闭 f1 = open("b.txt","w") with f1: #很显然,处理上面的那种方式写文件,咱们还可以这样使用with语句哟~
f1.write("") print(f1.closed) #测试f是否关闭 print("程序执行完毕") #试试代码执行结果如下:
True
True
程序执行完毕
十四.小试牛刀
1>.指定一个源文件,实现copy到目标目录
#!/usr/bin/env python
#_*_coding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
#EMAIL:y1053419035@qq.com def copy(src,dest):
with open(src) as f1:
with open(dest,"w") as f2:
f2.write(f1.read()) filename1 = "a.txt"
filename2 = "b.txt" f = open(filename1,"w+")
lines = ["admin","jason","https://www.cnblogs.com/yinzhengjie"]
f.writelines("\n".join(lines))
f.seek(0)
print(f.read())
f.close() copy(filename1,filename2) #以上代码输出结果如下:
admin
jason
https://www.cnblogs.com/yinzhengjie
admin
jason
https://www.cnblogs.com/yinzhengjie
执行上述脚本后a.txt文件内容
admin
jason
https://www.cnblogs.com/yinzhengjie
执行上述脚本后b.txt文件内容
2>.有一个文件,对其进行单词统计,不区分大小写,并显示单词重复最多的10个单词。
The Apache Hadoop software library is a framework that allows for the distributed processing of large data sets across clusters of computers using simple programming models. It is designed to scale up from single servers to thousands of machines, each offering local computation and storage. Rather than rely on hardware to deliver high-availability, the library itself is designed to detect and handle failures at the application layer, so delivering a highly-available service on top of a cluster of computers, each of which may be prone to failures.
hadoop.txt
#!/usr/bin/env python
#_*_coding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
#EMAIL:y1053419035@qq.com d = {} with open("hadoop.txt",encoding="utf8") as f:
for line in f:
words = line.split()
for word in map(str.lower,words):
d[word] = d.get(word,0) + 1 print(sorted(d.items(),key=lambda item :item[1],reverse=True)) #以上代码输出结果如下:
[('of', 6), ('to', 5), ('the', 4), ('is', 3), ('a', 3), ('library', 2), ('designed', 2), ('each', 2), ('and', 2), ('on', 2), ('apache', 1), ('hadoop', 1), ('software', 1), ('framework', 1), ('that', 1), ('allows', 1), ('for', 1), ('distributed', 1), ('processing', 1), ('large', 1), ('data', 1), ('sets', 1), ('across', 1), ('clusters', 1), ('computers', 1), ('using', 1), ('simple', 1), ('programming', 1), ('models.', 1), ('it', 1), ('scale', 1), ('up', 1), ('from', 1), ('single', 1), ('servers', 1), ('thousands', 1), ('machines,', 1), ('offering', 1), ('local', 1), ('computation', 1), ('storage.', 1), ('rather', 1), ('than', 1), ('rely', 1), ('hardware', 1), ('deliver', 1), ('high-availability,', 1), ('itself', 1), ('detect', 1), ('handle', 1), ('failures', 1), ('at', 1), ('application', 1), ('layer,', 1), ('so', 1), ('delivering', 1), ('highly-available', 1), ('service', 1), ('top', 1), ('cluster', 1), ('computers,', 1), ('which', 1), ('may', 1), ('be', 1), ('prone', 1), ('failures.', 1)]
解法一
#!/usr/bin/env python
#_*_coding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
#EMAIL:y1053419035@qq.com def makekey(s:str):
chars = set(r"""!'''#./\()[],*-""")
key = s.lower()
ret = []
for i ,c in enumerate(key):
if c in chars:
ret.append(" ")
else:
ret.append(c)
return "".join(ret).split() d = {} with open("hadoop.txt",encoding="utf8") as f:
for line in f:
words = line.split()
for wordlist in map(makekey,words):
for word in wordlist:
d[word] = d.get(word,0) + 1 for k,v in sorted(d.items(),key=lambda item:item[1],reverse=True):
print(k,v) #以上代码输出结果如下:
of 6
to 5
the 4
is 3
a 3
library 2
computers 2
designed 2
each 2
and 2
on 2
failures 2
apache 1
hadoop 1
software 1
framework 1
that 1
allows 1
for 1
distributed 1
processing 1
large 1
data 1
sets 1
across 1
clusters 1
using 1
simple 1
programming 1
models 1
it 1
scale 1
up 1
from 1
single 1
servers 1
thousands 1
machines 1
offering 1
local 1
computation 1
storage 1
rather 1
than 1
rely 1
hardware 1
deliver 1
high 1
availability 1
itself 1
detect 1
handle 1
at 1
application 1
layer 1
so 1
delivering 1
highly 1
available 1
service 1
top 1
cluster 1
which 1
may 1
be 1
prone 1
解法二
#!/usr/bin/env python
#_*_coding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
#EMAIL:y1053419035@qq.com def makekey(s:str):
chars = set(r"""!'''#./\()[],*-""")
key = s.lower()
ret = []
start = 0
length = len(key) for i ,c in enumerate(key):
if c in chars:
if start == i: #如果紧挨着还是特殊字符,start一定等于i
start += 1 #加1biangcontinue
continue
ret.append(key[start:i])
start = i + 1 #加1是跳过这个不需要的特殊字符c
else:
if start < len(key): #小于,说明还有有效的字符,而且一直到末尾
ret.append(key[start:])
return ret # print(makekey("os.path.exists(path)")) d = {} with open("hadoop.txt",encoding="utf8") as f:
for line in f:
words = line.split()
for wordlist in map(makekey,words):
for word in wordlist:
d[word] = d.get(word,0) + 1 for k,v in sorted(d.items(),key=lambda item:item[1],reverse=True):
print(k,v) #以上代码输出结果如下:
of 6
to 5
the 4
is 3
a 3
library 2
computers 2
designed 2
each 2
and 2
on 2
failures 2
apache 1
hadoop 1
software 1
framework 1
that 1
allows 1
for 1
distributed 1
processing 1
large 1
data 1
sets 1
across 1
clusters 1
using 1
simple 1
programming 1
models 1
it 1
scale 1
up 1
from 1
single 1
servers 1
thousands 1
machines 1
offering 1
local 1
computation 1
storage 1
rather 1
than 1
rely 1
hardware 1
deliver 1
high 1
availability 1
itself 1
detect 1
handle 1
at 1
application 1
layer 1
so 1
delivering 1
highly 1
available 1
service 1
top 1
cluster 1
which 1
may 1
be 1
prone 1
解法三
3>.实时监控一个文件内容
#!/usr/bin/env python
#_*_coding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
#EMAIL:y1053419035@qq.com import time MonitoringFile = "access.log" #定义我们需要监控的文件名称。 with open(MonitoringFile,'r',encoding="utf-8") as f:
f.seek(0,2) #表示将光标对应文件的末尾。
while True:
line = f.readline().strip() #读取每行的内容,并把换行符脱掉。
if line :
print("新增了一条记录:",line) #打印从文件末尾新增的每一行内容
time.sleep(0.5) #每次打印一行信息都需要睡0.5秒钟。
Python入门篇-文件操作的更多相关文章
- python基础篇(文件操作)
Python基础篇(文件操作) 一.初始文件操作 使用python来读写文件是非常简单的操作. 我们使用open()函数来打开一个文件, 获取到文件句柄. 然后通过文件句柄就可以进行各种各样的操作了. ...
- Python入门篇-StringIO和BytesIO
Python入门篇-StringIO和BytesIO 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.StringIO(用于文本处理) 1>.使用案例 #!/usr/bin ...
- python 历险记(三)— python 的常用文件操作
目录 前言 文件 什么是文件? 如何在 python 中打开文件? python 文件对象有哪些属性? 如何读文件? read() readline() 如何写文件? 如何操作文件和目录? 强大的 o ...
- Python入门篇-面向对象概述
Python入门篇-面向对象概述 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.语言的分类 面向机器 抽象成机器指令,机器容易理解 代表:汇编语言 面向过程 做一件事情,排出个 ...
- Python入门篇-functools
Python入门篇-functools 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.reduce方法 reduce方法,顾名思义就是减少 reduce(function,se ...
- Python入门篇-装饰器
Python入门篇-装饰器 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.装饰器概述 装饰器(无参) 它是一个函数 函数作为它的形参 返回值也是一个函数 可以使用@functi ...
- Python入门篇-返回值和作用域
Python入门篇-返回值和作用域 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.返回值 1>.返回值概述 Python函数使用return语句返回“返回值” 所有函数都 ...
- Python入门篇-函数、参数及参数解构
Python入门篇-函数.参数及参数解构 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.函数概述 1>.函数的作用即分类 函数 数学定义:y=f(x) ,y是x的函数,x ...
- Python入门篇-基础数据类型之整型(int),字符串(str),字节(bytes),列表(list)和切片(slice)
Python入门篇-基础数据类型之整型(int),字符串(str),字节(bytes),列表(list)和切片(slice) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.Py ...
随机推荐
- python -m SimpleHTTPServer搭建简单HTTP服务
PYTHON自带HTTP服务,命令: python -m SimpleHTTPServer 使用上述命令将当前目录发布到8000端口,为当前进行,不是后台运行 指定端口: python -m Simp ...
- 推荐一款好用的免费FTP客户端Filezilla
官网地址:https://filezilla-project.org/
- vue网页添加水印
水印添加方式:1.新建 waterMark.js 内容如下 let watermarkOption = {} let setWatermarkContent = (content) => { l ...
- 【C/C++开发】C++11:右值引用和转发型引用
右值引用 为了解决移动语义及完美转发问题,C++11标准引入了右值引用(rvalue reference)这一重要的新概念.右值引用采用T&&这一语法形式,比传统的引用T&(如 ...
- obj.GetType().GetCustomAttributes
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...
- MYSQL --Subquery returns more than 1 row查询结果多于一行
Subquery returns more than 1 row表示子查询返回了多行数据 例如: select * from table1 where table1.colums=(select co ...
- c++ pipe实现父子进程通信
1.父子进程通信pipe编程流程 -创建管道 -设置进程的输出到管道 -创建进程 -关闭管道写句柄 -读管道读句柄,把数据读到一个buffer里 2.注意事项 -读管道数据的时候,一定要关闭写句柄: ...
- 长乐国庆集训Day5
T1 方阵 题目 [题目描述] 小澳最近迷上了考古,他发现秦始皇的兵马俑布局十分有特点,热爱钻研的小澳打算在电脑上还原这个伟大的布局. 他努力钻研,发现秦始皇布置兵马俑是有一定规律的.兵马俑阵总共有n ...
- 安装rabbitMQ的PHP扩展
1.环境准备:centos 7.6+PHP7.3 2.安装rabbitmq-ctar xf rabbitmq-c-0.9.0.tar.gzcd rabbitmq-c-0.9.0mkdir build ...
- redis三种集群策略
主从复制 主数据库可以进行读写操作,当读写操作导致数据变化时会自动将数据同步给从数据库 从数据库一般都是只读的,并且接收主数据库同步过来的数据 一个master可以拥有多个slave,但是一个slav ...