您的位置:首页 > 编程语言 > Python开发

Python入门的36个例子 之 27 -> Add Something Into A File

2009-09-12 14:42 721 查看
源代码下载:下载地址在这里

e.g.1






# 030
aFile = file(r'C:/temp.txt', 'a')
aFile.write('又添加了一行。')
aFile.close()



output:






e.g.2






# 030
aFile = file(r'C:/temp.txt', 'a')
aFile.write('又添加了一行。')
aFile.close()



output:






e.g.3

实现根据原始文件有没有最后一行空行的情况来进行“完美添加”。

# 031
aFile = file(r'C:/temp.txt', 'r')
lastLine = ''
while True:
line = aFile.readline()
if len(line) == 0:
break
# end of if
lastLine = line
# end of while
aFile.close()
aFile = file(r'C:/temp.txt', 'a')
if not lastLine.endswith('/n'): # 说明源文件没有一个空行,需要重新另起一行
aFile.write('/n')
# end of if
aFile.write('这是新添加的一行!')
aFile.close()


此时无论原始文件是e.g.1的样子还是e.g.2的样子,结果都是:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐