Contents
文件处理是很多应用的基础功能, 相比其它语言 Python 对于文件处理更加容易; 下面由 Peyton McCullough 来解释其基础
- 文件处理是很多应用的重要功能,不许是用什么语言开发的.
- 这里我们要尝试各种使用对文件的操作:
- 读
- 写
- 补
- 或是其它古怪的事儿
- Let's get started.
1. 读和写 Reading and Writing
- 读/写 是对文件操作基础的基础了!
我们打开文件准备写:
1 fileHandle = open ( 'test.txt', 'w' )
这里的’w‘,指示我们将进行写
然后写入一些内容:
1 fileHandle.write ( 'This is a test.\nReally, it is.' )
这里写入文件的第一行是字串"This is a test.",第二行就是'“Really, it is.”'
这是使用 \n 换行符来实现的
最后我们要关闭文件句柄:
1 fileHandle.close()
- 正如所见,在Python 的对象世界中文件操作非常的方便
注意;“w”声明下的写入,将清除即有内容,如果你想追加内容 使用“a”模式
比如说:
1 fileHandle = open ( 'test.txt', 'a' ) 2 3 fileHandle.write ( '\n\n\nBottom line.' ) 4 5 fileHandle.close()
那么从外部文件读入内容:
1 2 fileHandle = open ( 'test.txt' ) 3 4 print fileHandle.read() 5 6 fileHandle.close()
- 这里打印出所有文件内容
也可以仅仅读一行:
1 2 fileHandle = open ( 'test.txt' ) 3 4 print fileHandle.readline() # "This is a test." 5 6 fileHandle.close()
也可以将所有行读取为一个列表:
1 fileHandle = open ( 'test.txt' ) 2 3 fileList = fileHandle.readlines() 4 5 for fileLine in fileList: 6 7 print '>>', fileLine 8 9 fileHandle.close()
读取文件时,Python 的读取位置会记录下来,例如:
1 fileHandle = open ( 'test.txt' ) 2 3 garbage = fileHandle.readline() 4 5 fileHandle.readline() # "Really, it is." 6 7 fileHandle.close()
- 只有第二行会打印出来
当然!我们可以告诉Python 从指定位置开始读取:
1 fileHandle = open ( 'test.txt' ) 2 3 garbage = fileHandle.readline() 4 5 fileHandle.seek ( 0 ) 6 7 print fileHandle.readline() # "This is a test." 8 9 fileHandle.close()
- 以上示例就是令Python 从文件的第一个字节开始读取
同样我们也可以获知识当前的读取位置信息:
1 fileHandle = open ( 'test.txt' ) 2 3 print fileHandle.readline() # "This is a test." 4 5 print fileHandle.tell() # "17" 6 7 print fileHandle.readline() # "Really, it is."
也可以仅仅一次读取文件的几个字节:
1 fileHandle = open ( 'test.txt' ) 2 3 print fileHandle.read ( 1 ) # "T" 4 5 fileHandle.seek ( 4 ) 6 7 print FileHandle.read ( 1 ) # "T"
在Windows 和 Macintosh中, 有时需要读写二进制文件,比如说;图片,可执行文件;那未使用“b”模式就好:
1 fileHandle = open ( 'testBinary.txt', 'wb' ) 2 3 fileHandle.write ( 'There is no spoon.' ) 4 5 fileHandle.close() 6 7 fileHandle = open ( 'testBinary.txt', 'rb' ) 8 9 print fileHandle.read() 10 11 fileHandle.close()
-- ZoomQuiet [2005-02-04 06:36:51]