Menu Close

python2 学习笔记之 文件

文件操作设计多个方面,比如文件的读取,写入,追加或者删除,也可能需要操作文件,比如需要将文件重命名。下面简单介绍一下文件在python中的基本操作.

打开一个文件

>>> open('test.py','r')  //用只读方式打开,这点和php一致,w为写,a为追加
<open file 'test.py', mode 'r' at 0x103e915d0>
>>> file = open('test.py','r')
>>> type(file)   //查看类型,结果为file
<type 'file'>
>>> id(file)
4360574560
>>>

如果文件是中文字符,那么可能会出现乱码

>>> file = open('test.py','r')
>>> file.read()
'hello \xe4\xbd\xa0\xe5\xa5\xbd\nhello china\n'
>>> 

可以使用codecs这个库来解决,并且这次我们新建一个文件

import codecs
#此处代替python的open函数,接受三个参数,分别是文件名、模式和编码
file = codecs.open('file1.txt','w','utf-8')
#写入几行文字,编码是unicode,每行都有一个\n,表示换行符
>>> file.write(u"早上没吃饭\n")
>>> file.write(u"中文吃的煎饼\n")
>>> file.write(u"晚上吃的煎饼和疙瘩汤\n")
#记得关闭file句柄
>>>file.close()

读取文件中内容,之前写了三行数据,这次每次读取一行,直至读完.

#读取一个文件,以只读utf8的格式
>>> file = codecs.open('file1.txt','r','utf-8')
#读取一行
>>> file.readline()
u'\u65e9\u4e0a\u6ca1\u5403\u996d\n'
#读取一行
>>> file.readline()
u'\u4e2d\u6587\u5403\u7684\u714e\u997c\n'
#读取一行
>>> file.readline()
u'\u665a\u4e0a\u5403\u7684\u714e\u997c\u548c\u7599\u7629\u6c64\n'
#注意这里,这里的读取类似于弹出,指针在不断移动
>>> file.readline()
u''
>>>

上面是读取一行内容,用的是readline()函数,还有一个函数是read(),用于读入多少字符

#读取一个字符
>>> print(file.read(1))
早
>>> print(file.read(1))
上
#读取两个字符
>>> print(file.read(2))
没吃
>>> print(file.read(3))
饭
中
>>> print(file.read(4))
文吃的煎
>>> print(file.read(5))
饼
晚上吃的
>>> print(file.read(6))
煎饼和疙瘩汤
#如果指针已经到了末尾,则返回空
>>> print(file.read(7))
>>>

有时候,我们可能会去操作文件,比如判断文件是否存在,获取修改文件名,这时候,我们可能需要os库

import os
#存在file1.txt
>>> os.path.exists('file1.txt')
True
#没有file2这个文件
>>> os.path.exists('file2.txt')
False
>>>
#需要文件名,第一个参数是现在的名字,第二个参数是想要修改的名字
os.rename("file1.txt",'file2.txt')
#如果参数1中的名字不存在,则会爆出一个 OSError: [Errno 2] No such file or directory

下面谈谈持久化,一般持久化是存储在db中,在文件中也可以做持久化,对象是json,我们需要用到shelve这个库。

#引入库
>>> import shelve
#新建一个文件,保存之后,会自动在文件后面加上.db后缀
>>> file = shelve.open('file1.shelve')
>>> file['key1'] ="value1"
>>> file['key2'] = "value2"
>>> file.close()
#上面是讲一些信息持久化,下面读取这些信息
>>> file = shelve.open('file1.shelve')
#直接打印
>>> print(file)
{'key2': 'value2', 'key1': 'value1'}
#读取字典索引
>>> print(file['key2'])
value2
#查看类型
>>> type(file)
<type 'instance'>
>>> dir(type)
['__abstractmethods__', '__base__', '__bases__', '__basicsize__', '__call__', '__class__', '__delattr__', '__dict__', '__dictoffset__', '__doc__', '__eq__', '__flags__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__instancecheck__', '__itemsize__', '__le__', '__lt__', '__module__', '__mro__', '__name__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasscheck__', '__subclasses__', '__subclasshook__', '__weakrefoffset__', 'mro']
>>> 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注