2016年11月21日 / 112次阅读
Python
写了一个简单的测试Python文件操作的函数,里面有几个细节:
1, 使用w方式打开文件,会将同名文件之前的内容全部删除;如果文件不存在,就是创建一个新文件;(使用a打开文件,如果文件不存在,一样是创建一个新文件)
2, 最好显示的制定文件的路径;
3, readline的结果长度等于0,表示EOF;
4, 关于flush函数:
一般的文件流操作都包含缓冲机制,write方法并不直接将数据写入文件,而是先写入内存中特定的缓冲区。flush方法是用来刷新缓冲区的,即将缓冲区中的数据立刻写入文件,同时清空缓冲区。正常情况下缓冲区满时,操作系统会自动将缓冲数据写入到文件中。至于close方法,原理是内部先调用flush方法来刷新缓冲区,再执行关闭操作,这样即使缓冲区数据未满也能保证数据的完整性。如果进程意外退出或正常退出时而未执行文件的close方法,缓冲区中的内容将会丢失。
Python的基本文件操作测试代码:
def testFile():
""" test file open write and close in Python
"""
#f1 = open('d:\\onlinepro\\kk.txt','w')
f1 = open('d:\\onlinepro\\kk1.txt','a') # a means Append to EOF
f1.write('it is a test baby\n')
f1.flush()
f1.close()
f2 = open('d:\\onlinepro\\kk.txt') # default is r,read
nn = 0
while True:
line = f2.readline()
if len(line) == 0: # 0 means EOF
break
else:
nn += 1
print('line',nn,line,end='') # skip the needless return
f2.close()
return
#---- End of Class: testFile
open是python的builtin函数,其它的函数都是file对象的函数!
Character | Meaning |
---|---|
'r' |
open for reading (default) |
'w' |
open for writing, truncating the file first |
'x' |
open for exclusive creation, failing if the file already exists |
'a' |
open for writing, appending to the end of the file if it exists |
'b' |
binary mode |
't' |
text mode (default) |
'+' |
open a disk file for updating (reading and writing) |
'U' |
universal newlines mode (deprecated) |
本文链接:https://www.maixj.net/ict/python-file-13651
《Python的基本文件操作》有1条留言
©Copyright 麦新杰 Since 2014 云上小悟独立博客版权所有 备案号:苏ICP备14045477号-1。云上小悟网站部分内容来源于网络,转载目的是为了整合信息,收藏学习,服务大家,有些转载内容也难以判断是否有侵权问题,如果侵犯了您的权益,请及时联系站长,我会立即删除。
w:write,新建一个文件,如果同名文件存在,无情清除并覆盖;a:append,追加内容,如果文件不存在,跟w效果一样;r,read,以只读的方式打开文件,文件不存在,异常,这是默认模式。更多帮助,使用help(open)。 [ ]