I/O 操作
- 文件的打开和创建
- 文件读取
- 文件写入
- 内容查找和替换
- 文件 删除 复制 重命名
- 目录操作
- file()
- file.read()
- file.write()
- file.close()
1.1 open
- file_handler = open( filename[, mode[, buffer]])
>>> help( open )
Help on built-in function open in module __builtin__:
open(...)
open(name[, mode[, buffering]]) -> file object
Open a file using the file() type, returns a file object. This is the
preferred way to open a file. See file.__doc__ for further information.
1.1.1 filename
- 相对路径的文件
- 局的路径的文件
- window下, 路径分隔符"\\" 或 "/"
1.1.2 mode
- r 只读(默认)
- r+ 读写, 先读后写-追加, 先写-从头开始覆盖
- w 写入, 清空, 没有则创建
- w+ 写入, 清空, 没有则创建(可写入输出)
- a 写入, 追加, 没有则创建
- a+ 读写, 追加, 没有则创建
- b 打开二级制的文件, 可与 r w a + 结合使用
- U 支持所有的换行符, \r \n \r\n
1.2 read -----file.read()
>>> help(file.read)
Help on method_descriptor:
read(...)
read([size]) -> read at most size bytes, returned as a string.
If the size argument is negative or omitted, read until EOF is reached.
Notice that when in non-blocking mode, less data than what was requested
may be returned, even if no size parameter was given.
E:\desktop\python\py_src>type a.txt
hello!
I'm Forward.
E:\desktop\python\py_src>python
######### file() ###############
>>> file_handler = open("a.txt")
>>> file_handler
<open file 'a.txt', mode 'r' at 0x012D6230>
>>> content = file_handler.read()
>>> content
"hello!\nI'm Forward.\n"
>>> print content
hello!
I'm Forward.
>>> file_handler.close()
>>> file_handler
<closed file 'a.txt', mode 'r' at 0x012D6230>
>>> file_handler.read()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file
######### file() ###############
>>> file_handler = file( "E:/desktop/python/py_src/a.txt" )
>>> file_handler
<open file 'E:/desktop/python/py_src/a.txt', mode 'r' at 0x012E6230>
>>> file_handler.read()
"hello!\nI'm Forward.\n"
>>> file_handler.close()
1.3 close ---- file.close()
>>> help( file.close )
Help on method_descriptor:
close(...)
close() -> None or (perhaps) an integer. Close the file.
Sets data attribute .closed to True. A closed file cannot be used for
further I/O operations. close() may be called more than once without
error. Some kinds of file objects (for example, opened by popen())
may return an exit status upon closing.
1.4 write ---- file.write()
>>> help( file.write )
Help on method_descriptor:
write(...)
write(str) -> None. Write string str to file.
Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.
>>> newfile = open("a.txt", "w")
>>> newfile.write( "hello, I'm a new file!" )
>>> newfile.flush()
>>> newfile.close()
>>> newfile = file( "a.txt" )
>>> newfile.read()
"hello, I'm a new file!"
>>> newfile.close()
- string = fileObject.readline([size])
- list = fileObject.readlines([size])
- contentString = fileObject.read([size])
- fileObject.next()
- fileObject.write(string)
- fileObject.writelines(list)
- fileObject.seek(offset, options)
- fileObject.flush()
2.1 read([size]) - string
- read(size) 每次读size个字节
- read() 一次读取所有内容
2.2 readline([size]) - string
- readline(size) 每次读一行中多少个字
- readline 每次读一行, 读到行末
>>> help(file.readline)
Help on method_descriptor:
readline(...)
readline([size]) -> next line from the file, as a string.
Retain newline. A non-negative size argument limits the maximum
number of bytes to return (an incomplete line may be returned then).
Return an empty string at EOF.
>>> afile = open("a.txt")
>>> afile.readline()
'\n'
>>> afile.readline()
'hello\n'
>>> afile.readline()
"I'm Forwar.\n"
>>> afile.readline()
"What's your name?\n"
>>> afile.readline()
'Bye!\n'
>>> afile.readline()
''
>>> afile.close()
2.3 readlines([size])
>>> help(file.readlines)
Help on method_descriptor:
readlines(...)
readlines([size]) -> list of strings, each a line from the file.
Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of bytes in the lines returned.
>>> afile = open("a.txt")
>>> afile.readlines()
['\n', 'hello\n', "I'm Forwar.\n", "What's your name?\n", 'Bye!\n']
>>> afile.close()
2.4 next()
- 读完, 会停止迭代, 不会像read...() 方法读完后返回空串
>>> help( file.next )
Help on wrapper_descriptor:
next(...)
x.next() -> the next value, or raise StopIteration
>>> afile = open("a.txt")
>>> afile.next()
'\n'
>>> afile.next()
'hello\n'
>>> afile.next()
"I'm Forwar.\n"
>>> afile.next()
"What's your name?\n"
>>> afile.next()
'Bye!\n'
>>> afile.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> afile.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> afile.close()
2.5 writelines(list)
>>> afile = open("a.txt")
>>> afile.close()
>>> afile = open("a.txt", "a")
>>> appendList = ["one\n", "two\n"]
>>> afile.writelines(appendList)
>>> afile.close()
2.6 seek(offset, whence) 移动文件指针
- whence = 0 文件开始
- whence = 1 当前位置
- whence = 2 文件末尾
>>> help(file.seek)
Help on method_descriptor:
seek(...)
seek(offset[, whence]) -> None. Move to new file position.
Argument offset is a byte count. Optional argument whence defaults to
0 (offset from start of file, offset should be >= 0); other values are 1
(move relative to current position, positive or negative), and 2 (move
relative to end of file, usually negative, although many platforms allow
seeking beyond the end of a file). If the file is opened in text mode,
only offsets returned by tell() are legal. Use of other offsets causes
undefined behavior.
Note that not all file objects are seekable.
>>> afile = open("a.txt")
>>> afile.read()
"\nhello\nI'm Forwar.\nWhat's your name?\nBye!\none\ntwo\n"
>>> afile.read()
''
>>> afile.seek(0)
>>> afile.read()
"\nhello\nI'm Forwar.\nWhat's your name?\nBye!\none\ntwo\n"
>>> afile.close()
- 文件的打开和创建
- 文件读取
- 文件写入
- 内容查找和替换
- 文件 删除 复制 重命名
- 目录操作
1. 文件读写
- open()- file()
- file.read()
- file.write()
- file.close()
1.1 open
- file_handler = open( filename[, mode[, buffer]])
>>> help( open )
Help on built-in function open in module __builtin__:
open(...)
open(name[, mode[, buffering]]) -> file object
Open a file using the file() type, returns a file object. This is the
preferred way to open a file. See file.__doc__ for further information.
1.1.1 filename
- 相对路径的文件
- 局的路径的文件
- window下, 路径分隔符"\\" 或 "/"
1.1.2 mode
- r 只读(默认)
- r+ 读写, 先读后写-追加, 先写-从头开始覆盖
- w 写入, 清空, 没有则创建
- w+ 写入, 清空, 没有则创建(可写入输出)
- a 写入, 追加, 没有则创建
- a+ 读写, 追加, 没有则创建
- b 打开二级制的文件, 可与 r w a + 结合使用
- U 支持所有的换行符, \r \n \r\n
1.2 read -----file.read()
>>> help(file.read)
Help on method_descriptor:
read(...)
read([size]) -> read at most size bytes, returned as a string.
If the size argument is negative or omitted, read until EOF is reached.
Notice that when in non-blocking mode, less data than what was requested
may be returned, even if no size parameter was given.
E:\desktop\python\py_src>type a.txt
hello!
I'm Forward.
E:\desktop\python\py_src>python
######### file() ###############
>>> file_handler = open("a.txt")
>>> file_handler
<open file 'a.txt', mode 'r' at 0x012D6230>
>>> content = file_handler.read()
>>> content
"hello!\nI'm Forward.\n"
>>> print content
hello!
I'm Forward.
>>> file_handler.close()
>>> file_handler
<closed file 'a.txt', mode 'r' at 0x012D6230>
>>> file_handler.read()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file
######### file() ###############
>>> file_handler = file( "E:/desktop/python/py_src/a.txt" )
>>> file_handler
<open file 'E:/desktop/python/py_src/a.txt', mode 'r' at 0x012E6230>
>>> file_handler.read()
"hello!\nI'm Forward.\n"
>>> file_handler.close()
1.3 close ---- file.close()
>>> help( file.close )
Help on method_descriptor:
close(...)
close() -> None or (perhaps) an integer. Close the file.
Sets data attribute .closed to True. A closed file cannot be used for
further I/O operations. close() may be called more than once without
error. Some kinds of file objects (for example, opened by popen())
may return an exit status upon closing.
1.4 write ---- file.write()
>>> help( file.write )
Help on method_descriptor:
write(...)
write(str) -> None. Write string str to file.
Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.
>>> newfile = open("a.txt", "w")
>>> newfile.write( "hello, I'm a new file!" )
>>> newfile.flush()
>>> newfile.close()
>>> newfile = file( "a.txt" )
>>> newfile.read()
"hello, I'm a new file!"
>>> newfile.close()
2. 文件对象方法
- fileObject.close()- string = fileObject.readline([size])
- list = fileObject.readlines([size])
- contentString = fileObject.read([size])
- fileObject.next()
- fileObject.write(string)
- fileObject.writelines(list)
- fileObject.seek(offset, options)
- fileObject.flush()
2.1 read([size]) - string
- read(size) 每次读size个字节
- read() 一次读取所有内容
2.2 readline([size]) - string
- readline(size) 每次读一行中多少个字
- readline 每次读一行, 读到行末
>>> help(file.readline)
Help on method_descriptor:
readline(...)
readline([size]) -> next line from the file, as a string.
Retain newline. A non-negative size argument limits the maximum
number of bytes to return (an incomplete line may be returned then).
Return an empty string at EOF.
>>> afile = open("a.txt")
>>> afile.readline()
'\n'
>>> afile.readline()
'hello\n'
>>> afile.readline()
"I'm Forwar.\n"
>>> afile.readline()
"What's your name?\n"
>>> afile.readline()
'Bye!\n'
>>> afile.readline()
''
>>> afile.close()
2.3 readlines([size])
>>> help(file.readlines)
Help on method_descriptor:
readlines(...)
readlines([size]) -> list of strings, each a line from the file.
Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of bytes in the lines returned.
>>> afile = open("a.txt")
>>> afile.readlines()
['\n', 'hello\n', "I'm Forwar.\n", "What's your name?\n", 'Bye!\n']
>>> afile.close()
2.4 next()
- 读完, 会停止迭代, 不会像read...() 方法读完后返回空串
>>> help( file.next )
Help on wrapper_descriptor:
next(...)
x.next() -> the next value, or raise StopIteration
>>> afile = open("a.txt")
>>> afile.next()
'\n'
>>> afile.next()
'hello\n'
>>> afile.next()
"I'm Forwar.\n"
>>> afile.next()
"What's your name?\n"
>>> afile.next()
'Bye!\n'
>>> afile.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> afile.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> afile.close()
2.5 writelines(list)
>>> afile = open("a.txt")
>>> afile.close()
>>> afile = open("a.txt", "a")
>>> appendList = ["one\n", "two\n"]
>>> afile.writelines(appendList)
>>> afile.close()
2.6 seek(offset, whence) 移动文件指针
- whence = 0 文件开始
- whence = 1 当前位置
- whence = 2 文件末尾
>>> help(file.seek)
Help on method_descriptor:
seek(...)
seek(offset[, whence]) -> None. Move to new file position.
Argument offset is a byte count. Optional argument whence defaults to
0 (offset from start of file, offset should be >= 0); other values are 1
(move relative to current position, positive or negative), and 2 (move
relative to end of file, usually negative, although many platforms allow
seeking beyond the end of a file). If the file is opened in text mode,
only offsets returned by tell() are legal. Use of other offsets causes
undefined behavior.
Note that not all file objects are seekable.
>>> afile = open("a.txt")
>>> afile.read()
"\nhello\nI'm Forwar.\nWhat's your name?\nBye!\none\ntwo\n"
>>> afile.read()
''
>>> afile.seek(0)
>>> afile.read()
"\nhello\nI'm Forwar.\nWhat's your name?\nBye!\none\ntwo\n"
>>> afile.close()