PYTHON 文件操作
对文件操作流程
- 打开文件,得到文件句柄并赋值给一个变量
- 通过句柄对文件进行操作
- 关闭文件
现有文件如下
Beautiful is better than ugly. 优美胜于丑陋 Explicit is better than implicit. 明了胜于晦涩 Simple is better than complex. 简单胜过复杂 Complex is better than complicated. 复杂胜过凌乱 Flat is better than nested. 扁平胜于嵌套 Sparse is better than dense. 间隔胜于紧凑 Readability counts. 可读性很重要 Special cases aren't special enough to break the rules. 即使假借特例的实用性之名,也不违背这些规则 Although practicality beats purity. 虽然实用性次于纯度 Errors should never pass silently. 错误不应该被无声的忽略 Unless explicitly silenced. 除非明确的沉默 In the face of ambiguity, refuse the temptation to guess. 当存在多种可能时,不要尝试去猜测 There should be one-- and preferably only one --obvious way to do it. 应该有一个,最好只有一个,明显能做到这一点 Although that way may not be obvious at first unless you're Dutch. 虽然这种 方式可能不容易,除非你是python之父 Now is better than never. 现在做总比不做好 Although never is often better than *right* now. 虽然过去从未比现在好 If the implementation is hard to explain, it's a bad idea. 如果这个实现不容易解释,那么它肯定是坏主意 If the implementation is easy to explain, it may be a good idea. 如果这个实现容易解释,那么它很可能是个好主意 Namespaces are one honking great idea -- let's do more of those! 命名空间是一种绝妙的理念,应当多加利用
基本操作
f=open('import this.txt') first_line = f.readline() print('first line:',first_line) #读一行,结果为first line: Beautiful is better than ugly. data = f.read() print(data) #阅读整个文件 f.close() #关闭文件
打开文件的模式有:
- r,只读模式(默认)。
- w,只写模式。【不可读;不存在则创建;存在则删除内容;】
- a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
- r+,可读写文件。【可读;可写;可追加】
- w+,写读
- a+,同a
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
- rU
- r+U
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
- rb
- wb
- ab
with语句
为了避免打开文件后忘记关闭,可以通过管理上下文自动关闭,即:
with open('import this.txt','r') as f: ...