1. 程式人生 > >Python file 方法

Python file 方法

Python file

#!/usr/bin/env python

# *_* coding=utf-8 *_*


"""

desc: 文件方法



#############################

file.read() #read([size]) -> read at most size bytes, returned as a string.

file.readline() readline([size]) -> next line from the file, as a string.

file.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.

file.xreadlines() xreadlines() -> returns self.

file.write() write(str) -> None. Write string str to file.

file.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.


file.truncate()

truncate([size]) -> None. Truncate the file to at most size bytes.

Size defaults to the current file position, as returned by tell().

file.seek()

seek(offset [,whence])方法改變當前文件的位置。Offset變量表示要移動的字節數。From變量指定開始移動字節的參考位置。

如果from被設為0,這意味著將文件的開頭作為移動字節的參考位置。如果設為1,則使用當前的位置作為參考位置。如果它被設為2,那麽該文件的末尾將作為參考位置。

file.flush()

file.tell() current file position, an integer (may be a long integer).

file.next()

file.close()



############不常用的方法#############

file.closed

file.mode

file.name

file.isatty() # true or false. True if the file is connected to a tty device.

file.readinto() #不用用這個

file.encoding # 不常用

file.errors # 不常用

file.newline # 不常用

file.softspace

file.fileno()

fileno() -> integer "file descriptor".

This is needed for lower-level file interfaces, such os.read().

###############################

version: 1.0

"""


fo= open("e:/temp.txt",'r')

print "文件名: ", fo.name

print "是否已關閉 : ", fo.closed

print "訪問模式 : ", fo.mode

print "末尾是否強制加空格 : ", fo.softspace






Python file 方法