乱读天书, 不求甚解
周祎骏的个人云笔记
Toggle navigation
乱读天书, 不求甚解
主页
Linux:系统配置
Linux:用户管理
Linux:优化排错
Linux:进程调度
Linux:文件系统
Linux:网络
Linux:系统服务
Linux:安全
Linux:内核
容器:Docker
容器:containerd
容器编排:Kubernetes
IAC:Terraform
大数据:Hadoop
大数据:Zookeeper
大数据:Hbase
消息队列:rsyslog
消息队列:kafka
数据库:MySQL
数据库:MongoDB
搜索引擎:Elasticsearch
时序数据库:OpenTSDB
网站服务:Nginx
编程:Bash
编程:Perl
编程:Python
编程:C
编程:JAVA
编程:Rust
版本控制:gitlab
知识管理:docusaurus
常用小工具
关于我
标签
python 0.05 输入输出/读写文件
2017-01-16 14:55:48
94
0
0
admin
> 这里介绍python 的输入输出,读写文件 #读取键盘输入 ##raw_input (常用) ``` [root@hadoop1 python]# cat input.py #!/usr/bin/python string = raw_input("Please type something:") #只读取一行 print string; [root@hadoop1 python]# ./input.py Please type something:abc abc ``` ##input (不常用) ``` [root@hadoop1 python]# cat input.py #!/usr/bin/python string = input("Please type something:") #读取一行,会运行它(相当于raw_input + eval ) print string; [root@hadoop1 python]# ./input.py Please type something:1+2 3 ``` *** #读写文件 ##open函数 file对象 = open(文件 [,模式][, buffer]) ###open 的参数 **buffer** 0 不缓存,1 缓存行,> 1 就是缓存的大小,< 0 就是系统默认的缓存大小 **模式** r / rb 只读/以二进制的格式只读,指针在文件开头 r+ / rb+ 读写/以二进制的格式读写,指针在文件开头 w / wb 只写/以二进制的格式只写,文件存在则覆盖文件,文件不存在则创建新文件 a / ab 追加/以二进制的格式追加,文件不存在就创建新文件,指针在文件结尾 a+ / ab+ 读写/以二进制的格式读写,指针在文件结尾 **文件对象的方法** file.read(num) 读取size 个字节,默认尽可能多的读 file.readline(size) 读取一行,仍受字节数限制 file.readlines(size) 读取多行,返回数组,一行一个元素,仍受字节数限制 file.next() 读取下一行 file.write("xx") 写入xx file.writelines(array) 写入文件,一个元素一行 file.tell() 当前offset 的位置 file.seek(num[,from]) 改变当前offset的位置num个字节数,from是开始移动字节的参考位置。 file.flush() 把缓冲器里的数据写入磁盘 file.close 刷新缓冲区未写入的信息,关闭句柄 file.closed 是否已经关闭文件句柄,关闭返回true file.mode 文件的访问方式 file.name 文件名称 file.fileno() 返回文件类型(整数) file.isatty() 是否连接到终端 **小例子** ``` #!/usr/bin/python import sys file = open(sys.argv[1]) while True: line = file.readline() if not line:break print line, file.close() ``` **Python新特性,文件对象是可迭代的:** ``` #!/usr/bin/python import sys file = open(sys.argv[1]) for line in file: print line, file.close() ``` **用 with open(xxx) as file 来读取文件,会自动在不用时关闭文件句柄,不需要close** ``` #!/usr/bin/python import sys with open(sys.argv[1]) as file: while True: line = file.readline() if not line:break print line, ```
上一篇:
python 0.04 子方法
下一篇:
python 0.06 执行动态代码
文档导航