17 Jul 2008

Python file operations

file is a special class in Python. Everything is object in python, so is file. It has attributes and methods. Now, let's study something about file:

file(name[, mode[, buffering]])


file() can create a file object, it's a build-in method. You may find someone else will use open(), actually it's an old version method. All parameters are passed in as string.

name: file name;
mode: there're 4 modes: r, w, a and U.
r: read mode;
w: write mode;
a: append mode;
U is a special mode. In Unix/Linux, line break is represented as '\n', while '\r\n' in Windows. U mode is used for support both type of line break.But python prefers '\n' to save these different line break symbols by a tuple.


file's attributes:

closed # if the file has been closed.
encoding # encoding type
mode # open mode
name # file name
newlines # line break mode, it's a tuple
softspace # boolean. indicates whether a space character needs to be printed before another value when using the print statement


file's mehods:

read([size]) # size is the byte length you want to read, read all file if it's not specified.
readline([size]) # read ONE line, maybe less than one line if size is smaller than the length of the line.
readlines([size]) # read several line into a list. size is the whole length.
write(str) # write str into file, there's no line break if you didn't specify.
writelines(seq) # write seq into file
close() # close the file. Although python will close a file while program don't need it anymore, but there's no guarantee. It's better to call this methods by yourselves.
flush() # write buffered content into the file.
fileno() # return a long file tag.
isatty() # is a terminal file(Unix/Linux).
tell() # current position from beginning of the file.
next() # return next line and move the pointer to next line.
seek(offset[,whence]) # move the pointer to offset. Usually calculated from the beginning except whence is specified. 0 beginning, 1 current position, 2 the end. Note: if the open mode is a or a+, the pointer will move to the end after every write operation.
truncate([size]) # cut the file into several segments with specified size, default cut untill reach the current position. If size is bigger than the file size, according to different OS, maybe there's no change, maybe add 0, maybe add random content.

No comments :

Post a Comment