Python Notes (8)
来源:互联网 发布:淘宝客有要交钱的 编辑:程序博客网 时间:2024/06/06 01:12
转载请注明出处:http://blog.csdn.net/cxsydjn/article/details/71303892
The note covers how to apply what just learned to a real-world application: writing data to a file.
Python notes of open courses @Codecademy.
File I/O (Input/Output)
f = open("output.txt", "w")
- This told Python to open
output.txt
in"w"
mode (“w” stands for “write”). - It stored the result of this operation in a file object,
f
.
- This told Python to open
- Four modes
"w"
: write-only mode"r"
: read-only mode"r+"
: read and write mode"a"
: append mode, which adds any new data you write to the file to the end of the file.
.write()
: writes to a file.- It takes a string argument.
str()
might be used.
- It takes a string argument.
.read()
: reads from a file..close()
: You must close the file after writing.
Advanced Functions
.readline()
: reading between the lines- If you open a file and call
.readline()
on the file object, you’ll get the first line of the file; subsequent calls to.readline()
will return successive lines.
- If you open a file and call
- Buffering Data
- During the I/O process, data is buffered: this means that it is held in a temporary location before being written to the file.
- Python doesn’t flush the buffer.
- If we don’t close a file, our data will get stuck in the buffer.
with
andas
- A way to get Python to automatically close files.
- File objects contain a special pair of built-in methods:
__enter__()
and__exit__()
. When a file object’s__exit__()
method is invoked, it automatically closes the file. Using
with
andas
to invoke the__exit__()
method, the syntax looks like this:with open("file", "mode") as variable: # Read or write to the file
.closed
- Python file objects have a
closed
attribute which isTrue
when the file is closed andFalse
otherwise. - By checking
file_object.closed
, we’ll know whether our file is closed and can callclose()
on it if it’s still open.
- Python file objects have a
External Resources
- Python Files I/O
0 0
- Python Notes (8)
- Python chapter 8 learning notes
- Python Notes
- Python notes
- Python Notes
- python notes
- Python notes
- Python Notes
- Python Notes
- Python Notes
- python notes
- python-notes
- Python Notes
- Python Cookbook Notes Chapter1
- Python Reviewing Notes
- My python/java notes
- Notes on Python
- Core Python Notes
- 近期总结+计划(5月份)
- 1008. Elevator (20)[C语言]
- [latex tikz]画曲线
- Collections.sort
- http://dl.hi-spider.com/pkg/free_unreg.pkg
- Python Notes (8)
- jQuery Ajax使用实例
- Android-消息机制(一):过程及源码分析
- 添加ArcGismap 内置图层属性模块
- 解决“Dynamic Web Module 3.0 requires Java 1.6 or newer.”错误
- Java自学001(简单介绍、常量与变量)
- 263. Ugly Number
- input,checkbox启用禁用
- react demo11 (添加组件事件处理)