Python实现给文件添加内容及得到文件信息的方法

WBOY
Release: 2016-06-10 15:11:15
Original
1100 people have browsed it

本文实例讲述了Python实现给文件添加内容及得到文件信息的方法。分享给大家供大家参考。具体分析如下:

经常会遇到给文件添加内容的时候,如果只是添加在文件的末尾,就比较简单了:

file = open(filename,'a')
file.write('hello')
file.close()

Copy after login

使用'a'模式打开文件后,指针默认指向文件末尾,即使你:

file.seek(0)
file.write('world')

Copy after login

字符串‘world'还是会加在文件的末尾,而不会是你想要的开始位置。

而我遇到的需求就是要在文件头添加东西啊,怎么办呢?不至于把里面东西全读出来,再写进去吧?

还好看到了'r+'这个模式(以前从来没有用过)

file = open(filename,'r+')
file.tell() #0L
file.write('begin')
file.close()

Copy after login

打开文件看看,是不是可以了呢;)

得到文件的修改时间:

>>> t = os.path.getmtime(path)
>>> t
1190626843
>>> type(t)
<type 'int'>
>>> os.stat(path)[8]
1190626843

Copy after login

得到文件的大小:

>>> os.stat(path)[6]
2808L
>>> os.path.getsize(path)
2808L

Copy after login

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!