Python 基础
- 文件I/O
-
打开和关闭文件-open()
file object = open(file_name [, access_mode][, buffering])
各个参数的细节如下:
- file_name:file_name变量是一个包含了你要访问的文件名称的字符串值。
- access_mode:access_mode决定了打开文件的模式:只读,写入,追加等。所有可取值见如下的完全列表。这个参数是非强制的,默认文件访问模式为只读®。
- buffering:如果buffering的值被设为0,就不会有寄存。如果buffering的值取1,访问文件时会寄存行。如果将buffering的值设为大于1的整数,表明了这就是的寄存区的缓冲大小。如果取负值,寄存区的缓冲大小则为系统默认。
-
File对象的属性
文件名: fo.name
是否已关闭 : fo.closed
返回被打开文件的访问模式:fo.mode
末尾是否强制加空格 : fo.softspace
-
打开模式
标识 模式 说明 r 只读 文件不存在报错 w 只写 文件不存在,新建文件 a 追加 文件不存在,新建文件 r+ 可读写 文件不存在报错,先读取文件,然后才能写入文件,反之,写不进内容 w+ 可读写 写读取文件,然后就无法读文件了。。。。 a+ 可读写 同上,原因是文件指针的位置决定了 -
目录
- ./ 当前目录
- …/上一级目录
- /下一级目录
-
write()
write()方法可将任何字符串写入一个打开的文件。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。
write()方法不会在字符串的结尾添加换行符(’\n’):
当存入非字符串对象是,数据必须转化为字节码,或者序列化
如果要写入一些不是字符串的东西, 那么将需要先进行转换:
f = open("/tmp/foo1.txt", "w") value = ('www.runoob.com', 14) s = str(value) f.write(s) f.flush() f.close()
-
read()
fo=open('content2.txt','r+') str=fo.read() print(str) fo.close()
-
readline() readlines()
fp_read=open('data.db','r',buffering=-1) line=fp_read.readline() #指针移动到第二行,读出所有行放到一个数组中 lines=fp_read.readlines() for i in lines: print(i) fp_read.close()
-
tell()
返回文件对象当前所处的位置, 它是从文件开头开始算起的字节数。fo.tell()
-
seek()
如果要改变文件当前的位置, 可以使用 f.seek(offset, from_what) 函数。
from_what 的值, 如果是 0 表示开头, 如果是 1 表示当前位置, 2 表示文件的结尾,例如:
- seek(x,0) : 从起始位置即文件首行首字符开始移动 x 个字符
- seek(x,1) : 表示从当前位置往后移动x个字符
- seek(-x,2):表示从文件的结尾往前移动x个字符
fp_read.seek(0) line=fp_read.readline() print(line)
-
json序列化对象
import json from unittwo4.fileHelper import saveFile,openFile users=[ {"id":'001',"user_id":"admin","user_password":"123","birthday":"2010-03-02","account":'300',"type":'1'}, {"id":'002',"user_id":"ddd","user_password":"123","birthday":"2010-03-02","account":'300',"type":'1'}, {"id":'003',"user_id":"fff","user_password":"123","birthday":"2010-03-02","account":'300',"type":'1'} ] str_user=json.dumps(users) #将python对象转化为json字符串 saveFile('users.db',str_user) content=openFile('users.db') dict_content=json.loads(content) #将json字符串转化为python对象
import json users=[ {"id":'001',"user_id":"admin","user_password":"123","birthday":"2010-03-02","account":'300',"type":'1'}, {"id":'002',"user_id":"ddd","user_password":"123","birthday":"2010-03-02","account":'300',"type":'1'}, {"id":'003',"user_id":"fff","user_password":"123","birthday":"2010-03-02","account":'300',"type":'1'} ] fp=open('users.json','w') json.dump(users,fp) #将python对象序列化,并且写入文件 fp_read=open('users.json','r') content=json.load(fp_read) #读入文件内容,并且反序列化为python内容 print(type(content)) for uu in content: print(uu['user_id'])
-
flush()
flush() 方法是用来刷新缓冲区的,即将缓冲区中的数据立刻写入文件,同时清空缓冲区,不需要是被动的等待输出缓冲区写入。
一般情况下,文件关闭后会自动刷新缓冲区,但有时你需要在关闭前刷新它,这时就可以使用 flush() 方法。
-
- 内存读写
- StringIO在内存中读写str
from io import StringIO my_string='abcdfg' fp=StringIO() fp.write(my_string[::-1]) my_string=my_string+fp.getvalue() print(my_string)
- 二进制数据,就需要使用BytesIO
from io import BytesIO fp_btye=BytesIO() fp_btye.write('中国'.encode()) print(fp_btye.getvalue().decode()
- StringIO在内存中读写str