Open a file using the file() type, returns a file object.
因此,两个函数其实都是一样的,下面只用file()。
在列举file()的作用时,使用help即是很好的方法,下面则是应重点关注的内容:
close(...)
| close() -> None or (perhaps) an integer. Close the file.
flush(...)
| flush() -> None. Flush the internal I/O buffer.
readline(...)
| readline([size]) -> next line from the file, as a string.
readlines(...)
| readlines([size]) -> list of strings, each a line from the file.
seek(...)
| seek(offset[, whence]) -> None. Move to new file position.
tell(...)
| tell() -> current file position, an integer (may be a long integer).
write(...)
| write(str) -> None. Write string str to file.
writelines(...)
| writelines(sequence_of_strings) -> None. Write the strings to the file.
xreadlines(...)
| xreadlines() -> returns self. 1.创建文件 --基本格式:
f = file('test.txt', 'w')
f = write('Hello World!')
['Hello World!\n', "I'm xpleaf.\n", 'Nice to meet you!\n']
>>> filelist[2] = 'See you next time!'
>>> print filelist
['Hello World!\n', "I'm xpleaf.\n", 'See you next time!']
·再以w的方式打开文件,用f.writelines(filelist)的方式写入,即可实现修改文件内容的目的; -xreadlines()
·不是先把文件内容全部写入内存,而是每读取一行才写入一行,写下一行时即对前面内存中的内容进行回收;
·在读取较大文件时,适宜采用这种办法。 --文件内容的遍历:使用readlines()
>>> f = file('test.txt', 'r')
>>> filelist = f.readlines()
>>> for eachline in filelist:
... print eachline,
...
Hello World!
I'm xpleaf.
Nice to meet you! 3.文件内容追加 --基本格式:
f = file('test.txt', 'a')
f = write('Hello World!')
f.close()
·文件内容追加到最后一行上,如果最后一行有'\n',则追加到下一行;
·write只能添加字符串,如果是数值或其它类型的数据类型,则需要使用str()进行转换; --实例:
>>> f = file('test.txt', 'a')
>>> f.write('See you next time!')