Python:文件操作
2016-05-17 16:12
211 查看
Python的文件操作较为简单,但是容易忘掉,然后自己就得去查询。
然而,有时查到的还并不是自己需要的,这样一来就会比较耗时。所以,自己决定写一个备忘再此,需要时回来看看即可。
详细介绍在这里:PythonFile
对于Python的文件操作,我们主要是了解它的:1.文件操作模式、2.常用方法、3.文件夹的创建
[TOC]
除了以上的部分,当然还有其它的。举个栗子:wb、ab、rb+、wb+和ab+等,这些都可以由上述的模式描述推测到用途。这些需要时在去查询即可。
f = open(‘test.txt’, ‘r’)
f.close()
除了以上方法,还有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
然而,有时查到的还并不是自己需要的,这样一来就会比较耗时。所以,自己决定写一个备忘再此,需要时回来看看即可。
详细介绍在这里:PythonFile
对于Python的文件操作,我们主要是了解它的:1.文件操作模式、2.常用方法、3.文件夹的创建
[TOC]
文件操作模式
Mode | 功能 |
---|---|
r | 以读方式打开 |
w | 以写方式打开(如果文件已存在,将清空) |
a | 以追加模式打开 |
r+ | 以读写模式打开 |
w+ | 以读写模式打开 |
a+ | 以读写模式打开 |
b | 以二进制模式打开 |
f = open(‘test.txt’, ‘r’)
f.close()
文件操作常用方法
调用函数 | 功能 |
---|---|
f.close() | 关闭文件 |
f.readline() | 读取一行 |
f.readlines() | 读取整个文件,并返回各行的数据列表 |
f.write(string) | 输入string |
向文件输入数据也可以通过重定向来实现:
../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动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法