python16 文件的读写
2013-08-30 09:26
351 查看
开始本章之前,先记住下面一些方法
close -- 关闭一个文件,同时对它进行保存。
read -- 读取一个文件的内容,你可以把内容赋值给一个变量。
readline -- 仅读取一行的内容。
truncate -- 清空文件,这个要小心使用。
write(stuff) -- 把stuff写到文件中。
看下代码ex16.py
学习要点:
1、CTRL-C 可以中止正在运行的python脚本
2、open方法添加了'w' 参数,表示以可写的方式打开一个文件,如果这个文件不存在,创建它
3、truncate把文件的内容全部清空了
4、write(stuff)把stuff写到文件中,注意以“\n”表示换行
5、close关闭并保
6、python -m pydoc file可以查看open更多的参数,'r','w','a'表示不同的意思。
close -- 关闭一个文件,同时对它进行保存。
read -- 读取一个文件的内容,你可以把内容赋值给一个变量。
readline -- 仅读取一行的内容。
truncate -- 清空文件,这个要小心使用。
write(stuff) -- 把stuff写到文件中。
看下代码ex16.py
from sys import argv script, filename = argv print "We're going to erase %r." % filename print "If you don't want that, hit CTRL-C (^C)." print "If you do want that, hit RETURN." raw_input("?") print "Opening the file..." target = open(filename, 'w') print "Truncating the file. Goodbye!" target.truncate() print "Now I'm going to ask you for three lines." line1 = raw_input("line 1: ") line2 = raw_input("line 2: ") line3 = raw_input("line 3: ") print "I'm going to write these to the file." target.write(line1) target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.write("\n") print "And finally, we close it." target.close()
学习要点:
1、CTRL-C 可以中止正在运行的python脚本
2、open方法添加了'w' 参数,表示以可写的方式打开一个文件,如果这个文件不存在,创建它
3、truncate把文件的内容全部清空了
4、write(stuff)把stuff写到文件中,注意以“\n”表示换行
5、close关闭并保
6、python -m pydoc file可以查看open更多的参数,'r','w','a'表示不同的意思。
相关文章推荐
- Python学习16:读写文件
- Learn Python The Hard Way学习(16) - 读写文件
- 笨方法学Python 习题 16: 读写文件
- 笨方法学python16习题 【读写文件】 最详解
- Learn Python The Hard Way学习(16) - 读写文件
- 笨方法学习Python-习题16: 读写文件
- python读写UCS-2 big/little endian(utf-16-be/utf-16-le)格式的文件
- python读写unicode文件之utf-16
- 笨办法学python习题16 读写文件
- python读写csv文件的实战
- python读写ini文件示例(python读写文件)
- Python文件读写
- python文件读写
- Python读写文件的操作
- python 读写CSV 文件
- Python实现的Excel文件读写类
- Python的IO操作之文件读写与序列化
- Python笔记-IO同步和异步、 读写文件、StringIO和BytesIO
- Python 文件读写操作实例详解
- 【Python】Learn Python the hard way, ex16 读写文件