reading/writing files in Python
2024-08-30 23:33:28
file types:
- plaintext files, such as .txt .py
- Binary files, such as .docx, .pdf, iamges, spreadsheets, and executable programs(.exe)
steps to read/write files
- call the
open()
function to return aFile object
- Call the
read()
orwrite()
method on the File object - Close the file by calling the
close()
method on the File object
To open the file in 'reading plaintext' mode (read mode):
>>> helloFile=open('/user/kaiming/Python/hello.txt')
>>> helloFile=open('/user/kaiming/Python/hello.txt', 'r')
where 'r' stands for read mode
the call to open()
returns a File object
, and assigned to the variable helloFile
To get a list of string values from the file, one string for each line of text, use readline()
function
Writing to files >>> open ('hello.txt', 'w') # write mode >>> open ('hello.txt', 'a') # append mode
Note:
- when a file is opened in read mode, Python lets you only read data from
the file; you can't write or modify it in any way.
- if the filename passed to
open()
does not exist, both
write and append mode will create a new, blank file
>>> baconFile = open('bacon.txt', 'w') # create a blank file named 'bacon.txt'
>>> baconFile.write('Hello world!\n')
13
>>> baconFile.close()
>>> baconFile = open('bacon.txt', 'a')
>>> baconFile.write('Bacon is not a vegetable.')
25
>>> baconFile.close()
>>> baconFile = open('bacon.txt')
>>> content = baconFile.read()
>>> baconFile.close()
>>> print(content)
Hello world!
Bacon is not a vegetable.
最新文章
- 移动到web整理
- jquery插件之tab标签页或滑动门
- Neo4j Cypher运行示例
- nodejs-express 报错View is not a constructor
- BAT批处理(二)
- git 第一次初始化
- U3D UGUI学习2 - Canvas
- Android SDK Manager无法更新问题解决
- 再也不用担心ie下console.log报错了。。。
- Unity Diffuse Metal Shader Mod
- python【第二篇】列表、元组、字典及文件操作
- 10 Powerful Apache Modules--reference
- C# 2 运算符 if
- 2016WHD.china世界云计算日·北京站即将召开
- ASP.NET MVC 使用TempData
- Banner图二三事
- 7.12 其他面向对象设计原则3: 依赖倒置原则DIP
- 2019-4-22 jdbc学习笔记
- Spark中master与worker的进程RPC通信实现
- vux安装中遇到的坑
热门文章
- Code First:Fluent API
- E20170602-ts
- Android内存管理(14)*使用开源库LeakCanary检查内存泄漏
- log4net 简易封装
- Redis基础---消息通信模式
- multiprocessing的进程通信Pipe和Queue
- js操作Attribute,控件的各种属性.....maxlength,style...
- Windows下重置MySQL密码【MYSQL】
- 为什么我的对象被 IntelliJ IDEA 悄悄的修改了?
- ES6:Generator函数(1)