Python(四)
来源:互联网 发布:司法考试培训班 知乎 编辑:程序博客网 时间:2024/06/01 10:35
文件操作:
打开文件:open()
<variable> = open (<name>, <mode>)<name>磁盘文件名称<mode>打开模式
打开模式:
r ,只读。如果文件不存在,则输出错误。w ,只写。如果文件不存在,则自动创建文件。a ,附加到文件末尾。rb ,只读二进制文件,如果文件不存在,则输出错误。wb ,只写二进制文件,如果文件不存在,则自动创建文件。ab ,附加到二进制文件末尾。r+ ,表示读写。
文件基本操作:写入,读出,定位
文件其他操作:追加、计算等
#打开文本文件infile = open(“numbers.dat”,“r”)#打开音频文件infile = open("music.mp3","rb")
文件读取:
read() 返回值为包含整个文件内容的一个字符串。readline() 返回值为文件下一行内容的字符串。readlines() 返回值为整个文件内容的列表,每项是以换行符为结尾的一行字符串。文件写入:
write() 把含有文本数控或二进制数据块的字符串写入文件
writelines() 针对列表操作,接受一个字符串列表作为参数,将它们写入文件,并且结束符不会被自动加入。
文件遍历,通用的代码框架:
file = open(someFile,"r")for line in file.readlines(): #处理一行文件内容file.close()
文件遍历,简化的代码框架:
file = open(someFule,"r")for line in file: #处理一行文件内容file.close()
文件拷贝代码示例:
# dothedocument3.py#encoding=utf-8# 文件拷贝def main(): # 用户输入文件名 f1 = input("Enter a souce file:").strip() f2 = input("Enter a souce file:").strip() # 打开文件 infile = open(f1,"r") outfile = open(f2,"w") # 拷贝数据 countLines = countChars = 0 for line in infile: countLines += 1 countChars += len(line) outfile.write(line) print(countLines,"lines and ",countChars," chats copied") infile.close() outfile.close()main()
阅读全文
0 0
- python集锦(四)
- python理论学习(四)
- python笔记(四)
- Python学习(四)
- 学习Python(四)
- python实用技巧(四)
- python笔记(四)
- Python(四)字典
- python爬虫(四)
- python入门(四)
- python入门(四)
- python新手入门(四)
- python基础(四)
- python学习(四)
- python练习(四)
- python基础(四)
- Python入门(四)
- Python(四)
- MyBatis的级联查询(association 进行分布查询)
- textarea高度自适应增高;chrome下clientHeight,offsetHeight和scrollHeight
- 租了一个月的腾讯云服务, 玩ubuntu爽爽哒
- MPI_Send和MPI_Recv(初识1)
- JDBC学习06-DBUtils下载和使用
- Python(四)
- Android 多语言支持
- uva116
- vue 路由组件
- [Oracle] CPU/PSU补丁安装详细教程
- 葡萄城ComponentOne全功能开发控件套包发布2017V3 新版本
- 图
- 使用Gradle构建多个不同applicationId包
- C# SpinWait 实现