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

Python:文件操作

2016-05-17 16:12 120 查看
Python的文件操作较为简单,但是容易忘掉,然后自己就得去查询。

然而,有时查到的还并不是自己需要的,这样一来就会比较耗时。所以,自己决定写一个备忘再此,需要时回来看看即可。

详细介绍在这里:PythonFile

对于Python的文件操作,我们主要是了解它的:1.文件操作模式、2.常用方法、3.文件夹的创建

[TOC]

文件操作模式

Mode功能
r以读方式打开
w以写方式打开(如果文件已存在,将清空)
a以追加模式打开
r+以读写模式打开
w+以读写模式打开
a+以读写模式打开
b以二进制模式打开
除了以上的部分,当然还有其它的。举个栗子:wb、ab、rb+、wb+和ab+等,这些都可以由上述的模式描述推测到用途。这些需要时在去查询即可。

f = open(‘test.txt’, ‘r’)

f.close()

文件操作常用方法

调用函数功能
f.close()关闭文件
f.readline()读取一行
f.readlines()读取整个文件,并返回各行的数据列表
f.write(string)输入string
除了以上方法,还有f.fileno()、f.flush()、f.isatty()、f.read([count])、f.seek(offset[, where])、f.tell()、f.truncate([size])等等。

向文件输入数据也可以通过重定向来实现:

../current>>f = open(‘test.txt’, ‘w’)

../current>>print >> f, ‘Cause we are the champion, no time for loser!\nWe are the one, we are the children!’

../current>>f.close()

../current>>f = open(‘test.txt’, ‘r’)

../current>>for line in f.readlines():

.. print line

Cause we are the champion, no time for loser!

We are the one, we are the children!

../current>>f.close()

文件夹的创建

许多时候,我们的创建文件较多,需要分类。那么,以文件夹进行区分是再直接不过的方式了

import os

now_time_ms = datetime.datetime.now() #the current time

now_tims_d = now_time_ms.strftime(“%Y-%m-%d”) #the date of today:yyyy-mm-dd

if not os.path.exists(now_tims_d): #create the file of today

os.mkdir(now_tims_d)

if not os.path.exists(now_tims_d+”/url”):

os.mkdir(now_tims_d+”/url”)

if not os.path.exists(now_tims_d+”/ProductData”):

os.mkdir(now_tims_d+”/ProductData”)

以上是我写爬虫时用到的文件夹操作,以时间命名文件夹。

参考资料:

http://maincoolbo.iteye.com/blog/626655
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python