标签:python file对象操作方法 file-like对象操作 文件操作方法
IO中读写文件操作方法汇总!----The_Third_Wave的学习笔记!
本文由@The_Third_Wave(Blog地址:http://blog.csdn.net/zhanh1218)原创。不定期更新,有错误请指正。
Sina微博关注:@The_Third_Wave
如果这篇博文对您有帮助,为了好的网络环境,不建议转载,建议收藏!如果您一定要转载,请带上后缀和本文地址。
class file(object)
| file(name[, mode[, buffering]]) -> file object
|
| Open a file. The mode can be ‘r‘, ‘w‘ or ‘a‘ for reading (default), writing or appending. The file will be created if it doesn‘t exist when opened for writing or appending; it will be truncated when opened for writing. Add a ‘b‘ to the mode for binary
files. Add a ‘+‘ to the mode to allow simultaneous reading and writing. If the buffering argument is given, 0 means unbuffered, 1 means line buffered, and larger numbers specify the buffer size. The preferred way to open a file is with the builtin open()
function. Add a ‘U‘ to mode to open the file for input with universal newline support. Any line ending in the input file will be seen as a ‘\n‘ in Python. Also, a file so opened gains the attribute ‘newlines‘; the value for this attribute is one of None
(no newline read yet), ‘\r‘, ‘\n‘, ‘\r\n‘ or a tuple containing all the newline types seen.
打开文件。默认为reading模式(r),mode参数可以为 ‘r‘-reading , ‘w‘-writing or ‘a‘ -appending(追加)。当为writing模式或者appending模式时如果文件不存在可能被创建。writing模式时文件可能被截断。‘b‘模式用于二进制文件。‘+‘模式用于允许同时读写文件。
buffering:0,无缓冲;1,一行缓冲,数字越大,意味着缓冲区越大。
打开文件推荐内置函数open()。‘U‘模式为通用换行符支持输入打开文件。在Python中任何行结束符在输入文件将被视为‘\n‘。同时,文件打开增加属性‘newlines‘;此属性的值为None(没有新行可读时),‘r‘,‘n‘,‘\r\n‘或一个元组包含所有换行符的类型。
| ‘U‘ cannot be combined with ‘w‘ or ‘+‘ mode.
| ‘U‘不能和‘w‘或者‘+‘模式一起使用。
Methods defined here:
| 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.
设置数据属性.closed()为真。关闭的文件不能用于进一步的I/O操作(关闭文件就没办法在操作了)!无错误时可以被调用1次以上。某些种类的文件对象可能在关闭时返回一个状态值(例如:popen()打开的文件对象)。【注:os.popen()】
| fileno(...)
| fileno() -> integer "file descriptor".
| 返回值为整数(文件描述符)
| This is needed for lower-level file interfaces, such os.read().
| 需要1个低级的文件接口,例如os.read()
| flush(...)
| flush() -> None. Flush the internal I/O buffer 把缓冲区的内容写入磁盘!(write()之后需要用到)
| isatty(...)
| isatty() -> true or false. True if the file is connected to a tty device.返回文件是否是一个终端设备文件【unix系统中使用】。
| next(...)
| x.next() -> the next value, or raise StopIteration【也就是生成器的方法,返回下一行。】
|
| 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.
如果size为负数或者缺省,读取整个文件。注意在非阻塞模式下,数据返回的可能比实际请求返回的少,及时size参数没有给定(也就是缺省状态)!
| readinto(...)
| readinto() -> Undocumented. Don‘t use this; it may go away.
|
| 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.
保持新行。非负的size参数限制返回的最大的字节数(也就是可能会返回不完整的行)。文件结束时返回空字符串!
| 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.不断调用readline()方法并且返回一个每行数据(str)组成的list。【list(f)效果相同;size参数2.7.6实测使用没变化和read()读出来的相同,待进一步确定。】
| 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.
| 将文件打操作标记移到offset的位置。这个offset一般是相对于文件的开头来计算的,一般为正数。但如果提供了whence参数就不一定了,whence可以为0表示从头开始计算,1表示以当前位置为原点计算。2表示以文件末尾为原点进行计算。需要注意,如果文件以a或a+的模式打开,每次进行写操作时,文件操作标记会自动返回到文件末尾。
| tell(...)
| tell() -> current file position, an integer (may be a long integer).
| 返回文件当前位置,一个整数(可能是一个长整数)。【也就是一行一行读写文件时,现在光标所在位置(以文件开头为原点)】
| truncate(...)
| truncate([size]) -> None. Truncate the file to at most size bytes.按size的值截取文件。
|
| Size defaults to the current file position, as returned by tell()。【说明太简单,待确定】
|
| write(...)
| write(str) -> None. Write string str to file.
| 写字符串到文件,返回值为None
| Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.执行flush()或者close()之后才能真正写到文件。
| writelines(...)
| writelines(sequence_of_strings) -> None. Write the strings to the file.
|
| Note that newlines are not added. The sequence can be any iterable object producing strings. This is equivalent to calling write() for each string.请注意,没有添加新行。sequence_of_strings可为字符串构成的迭代器。这相当于调用write()写每个字符串。【不会自动换行,也就是说不会自动添加换行符;sequence_of_strings可以使list、tuple、dict(保持迭代器中内容为str)。】
| xreadlines(...)
| xreadlines() -> returns self.
| 返回自身
| For backward compatibility. File objects now include the performance optimizations previously implemented in the xreadlines module.向后兼容。文件对象包括性能优化以前实施的xreadlines模块。
|
| ----------------------------------------------------------------------
文件读写
一、普通型
>>> f = open("C:\\Users\\admin\\Desktop\\222.txt",'r')
>>> print f.read()
@The Third Wave(Blog地址:http://blog.csdn.net/zhanh1218)文件读写!
>>> f.closed
False
>>> f.close()
>>> f.closed
True
>>>
每次读完文件后,需要close()方法关闭文件对象。文件使用完毕后必须关闭,因为:文件对象会占用操作系统的资源;操作系统同一时间能打开的文件数量有限。
二、try--except--finally
>>> try:
f = open("C:\\Users\\admin\\Desktop\\222.txt",'r')
print f.read()
print f.closed
except:
print "error"
raise
finally:
if f:
f.close()
print f.closed
@The Third Wave(Blog地址:http://blog.csdn.net/zhanh1218)文件读写!
False
True
>>>
比较麻烦!
三、文艺型
使用with as语句,推荐!!!
>>> with open("C:\\Users\\admin\\Desktop\\222.txt",'r') as f:
print f.read()
print f.closed
@The Third Wave(Blog地址:http://blog.csdn.net/zhanh1218)文件读写!
False
>>> f.closed
True
>>>
本文由@The_Third_Wave(Blog地址:http://blog.csdn.net/zhanh1218)原创。不定期更新,有错误请指正。
Sina微博关注:@The_Third_Wave
如果这篇博文对您有帮助,为了好的网络环境,不建议转载,建议收藏!如果您一定要转载,请带上后缀和本文地址。
Python:file/file-like对象方法详解【单个文件读写】,布布扣,bubuko.com
Python:file/file-like对象方法详解【单个文件读写】
标签:python file对象操作方法 file-like对象操作 文件操作方法
原文地址:http://blog.csdn.net/zhanh1218/article/details/27112467