Python基础知识05-文件处理
一.文件处理流程
- 打开文件,得到文件句柄并赋值给一个变量
- 通过句柄对文件进行操作
- 关闭文件
关关雎鸠,在河之洲,窈窕淑女,what's your QQ ! 但使龙城飞将在, come on baby don't be shy.... 急急如律令,do blow job in the rain 天上掉下个林妹妹,whatever i'm gay 两情若是长久时,you jump ,I jump 问君能有几多愁,as a boy without a girl 床前明月光,there's something wrong~ 问世间情为何物,what the **** can I do 众里寻他千百度,蓦然回首,Hey,how do you do 云中谁寄锦书来?super high ,suck guy!
二.基本操作
2.1 文件操作基本流程初探
f = open('file.txt') #打开文件 first_line = f.readline() print 'first line:',first_line #读一行 print '我是分隔线'.center(50,'-') data = f.read() # 读取剩下的所有内容,文件大时不要用。 print data #打印读取内容 f.close() #关闭文件
2.2 文件编码
查看编码格式
import chardet f = open('file.txt') #打开文件 first_line = f.readline() print chardet.detect(first_line) #运行结果 {'confidence': 1.0, 'language': '', 'encoding': 'UTF-8-SIG'}
2.3 文件打开模式
open函数
文件句柄 = open('文件路径', '模式')
open函数有很多的参数,常用的是file,mode和encoding,open(file[, mode[, buffering[, encoding[, errors[, newline[, closefd=True]]]]]])
- file文件位置,需要加引号
- mode文件打开模式,见下面3
- buffering的可取值有0,1,>1三个,0代表buffer关闭(只适用于二进制模式),1代表line buffer(只适用于文本模式),>1表示初始化的buffer大小;
- encoding表示的是返回的数据采用何种编码,一般采用utf8或者gbk;
- errors的取值一般有strict,ignore,当取strict的时候,字符编码出现问题的时候,会报错,当取ignore的时候,编码出现问题,程序会忽略而过,继续执行下面的程序。
- newline可以取的值有None, \n, \r, ”, ‘\r\n',用于区分换行符,但是这个参数只对文本模式有效;
- closefd的取值,是与传入的文件参数有关,默认情况下为True,传入的file参数为文件的文件名,取值为False的时候,file只能是文件描述符,什么是文件描述符,就是一个非负整数,在Unix内核的系统中,打开一个文件,便会返回一个文件描述符。
Python中file()与open()区别
两者都能够打开文件,对文件进行操作,也具有相似的用法和参数,但是,这两种文件打开方式有本质的区别,file为文件类,用file()来打开文件,相当于这是在构造文件类,而用open()打开文件,是用python的内建函数来操作,建议使用open。
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
打开文件的模式有: r,只读模式【默认模式,文件必须存在,不存在则抛出异常】 w,只写模式【不可读;不存在则创建;存在则清空内容】 x,只写模式【不可读;不存在则创建,存在则报错】 a,追加模式【可读;不存在则创建;存在则只追加内容】 "+" 表示可以同时读写某个文件 r+,读写【可读,可写】 w+,写读【可读,可写】 x+,写读【可读,可写】 a+,写读【可读,可写】 "b"表示以字节的方式操作 rb 或 r+b wb 或 w+b xb 或 w+b ab 或 a+b 注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码 "U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用) rU 或 r+U "b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注) rb 或 wb 或 ab
class file(object): def close(self): # real signature unknown; restored from __doc__ 关闭文件 """ close() -> None or (perhaps) an integer. Close the file. Sets data attribute .closed to True. A closed file cannot be used for further I/O operations. close() may be called more than once without error. Some kinds of file objects (for example, opened by popen()) may return an exit status upon closing. """ def fileno(self): # real signature unknown; restored from __doc__ 文件描述符 """ fileno() -> integer "file descriptor". This is needed for lower-level file interfaces, such os.read(). """ return 0 def flush(self): # real signature unknown; restored from __doc__ 刷新文件内部缓冲区 """ flush() -> None. Flush the internal I/O buffer. """ pass def isatty(self): # real signature unknown; restored from __doc__ 判断文件是否是同意tty设备 """ isatty() -> true or false. True if the file is connected to a tty device. """ return False def next(self): # real signature unknown; restored from __doc__ 获取下一行数据,不存在,则报错 """ x.next() -> the next value, or raise StopIteration """ pass def read(self, size=None): # real signature unknown; restored from __doc__ 读取指定字节数据 """ read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given. """ pass def readinto(self): # real signature unknown; restored from __doc__ 读取到缓冲区,不要用,将被遗弃 """ readinto() -> Undocumented. Don't use this; it may go away. """ pass def readline(self, size=None): # real signature unknown; restored from __doc__ 仅读取一行数据 """ readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF. """ pass def readlines(self, size=None): # real signature unknown; restored from __doc__ 读取所有数据,并根据换行保存值列表 """ readlines([size]) -> list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read. The optional size argument, if given, is an approximate bound on the total number of bytes in the lines returned. """ return [] def seek(self, offset, whence=None): # real signature unknown; restored from __doc__ 指定文件中指针位置 """ seek(offset[, whence]) -> None. Move to new file position. Argument offset is a byte count. Optional argument whence defaults to 0 (offset from start of file, offset should be >= 0); other values are 1 (move relative to current position, positive or negative), and 2 (move relative to end of file, usually negative, although many platforms allow seeking beyond the end of a file). If the file is opened in text mode, only offsets returned by tell() are legal. Use of other offsets causes undefined behavior. Note that not all file objects are seekable. """ pass def tell(self): # real signature unknown; restored from __doc__ 获取当前指针位置 """ tell() -> current file position, an integer (may be a long integer). """ pass def truncate(self, size=None): # real signature unknown; restored from __doc__ 截断数据,仅保留指定之前数据 """ truncate([size]) -> None. Truncate the file to at most size bytes. Size defaults to the current file position, as returned by tell(). """ pass def write(self, p_str): # real signature unknown; restored from __doc__ 写内容 """ write(str) -> None. Write string str to file. Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written. """ pass def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__ 将一个字符串列表写入文件 """ writelines(sequence_of_strings) -> None. Write the strings to the file. Note that newlines are not added. The sequence can be any iterable object producing strings. This is equivalent to calling write() for each string. """ pass def xreadlines(self): # real signature unknown; restored from __doc__ 可用于逐行读取文件,非全部 """ xreadlines() -> returns self. For backward compatibility. File objects now include the performance optimizations previously implemented in the xreadlines module. """ pass
2.4 文件内置函数flush
flush原理:
- 文件操作是通过软件将文件从硬盘读到内存
- 写入文件的操作也都是存入内存缓冲区buffer(内存速度快于硬盘,如果写入文件的数据都从内存刷到硬盘,内存与硬盘的速度延迟会被无限放大,效率变低,所以要刷到硬盘的数据我们统一往内存的一小块空间即buffer中放,一段时间后操作系统会将buffer中数据一次性刷到硬盘)
- flush即,强制将写入的数据刷到硬盘
滚动条:
import sys,time for i in range(10): sys.stdout.write('#') sys.stdout.flush() time.sleep(1)
2.5 文件内光标内置函数
read & readline & readlines:
- .read() 每次读取整个文件,它通常将读取到的文件内容放到一个字符串变量中,也就是说 .read() 生成文件内容是一个字符串类型;
- .readline()每只读取文件的一行,通常也是读取到的一行内容放到一个字符串变量中,返回str类型;
- .readlines()每次按行读取整个文件内容,将读取到的内容放到一个列表中,返回list类型。
f = open('file.txt') #打开文件 print f.read() #打开整个文件 for i in f.readline(): #读取文件的一行 print i x = f.readlines() #读取整个文件放在一个迭代器中 for i in x: print i
seek:seek(offset,where)
- seek() 方法用于移动文件读取指针到指定位置。
- fileObject.seek(offset[, whence])
- offset -- 开始的偏移量,也就是代表需要移动偏移的字节数
- whence:可选,默认值为 0。给offset参数一个定义,表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起
- 没有返回值。需要注意的是,如果该文件被打开或者使用'a'或'A+'追加,任何seek()操作将在下次写撤消。
- 如果该文件只打开使用“a”的追加模式写,这种方法本质上是一个空操作,但读使能(模式'a+'),它仍然在追加模式打开的文件非常有用。
- 如果该文件在文本模式下使用“t”,只有tell()返回的偏移开都是合法的。使用其他偏移会导致不确定的行为。
- 请注意,并非所有的文件对象都是可搜索。
tell:
- 获取当前文件读取指针的位置,受seek、readline、read、readlines影响,不受truncate影响
- file.tell() 注: 此方法没有参数
示例:
fo = open("file.txt", "r+") print "Name of the file: ", fo.name line = fo.readline() print "Read Line: %s" % (line) fo.seek(0, 0) line = fo.readline() pos = fo.tell() print "Read Line: %s" % (line) print "Current Position: %d" % (pos) fo.close() #输出结果 Name of the file: file.txt Read Line: 关关雎鸠,在河之洲,窈窕淑女,what's your QQ ! Read Line: 关关雎鸠,在河之洲,窈窕淑女,what's your QQ ! Current Position: 66
- truncate() 方法用于截断文件的大小,如果可选的尺寸参数存在,该文件被截断(最多)的大小。
- fileObject.truncate( [ size ])
- 如果指定了可选参数 size,则表示截断文件为 size 个字符。 如果没有指定 size,则从当前位置起截断;截断之后 size 后面的所有字符被删除。
- 此方法不会在当文件工作在只读模式打开。
fo = open("file.txt", "r+") print "Name of the file: ", fo.name line = fo.readline() print "Read Line: %s" % (line) fo.truncate() fo.truncate(10) #截取10个字节 line = fo.readline()# 截断剩下的字符串 print "Read Line: %s" % (line) fo.close() #输出结果 Name of the file: file.txt Read Line: 关关雎鸠,在河之洲,窈窕淑女,what's your QQ ! Read Line:
2.6 上下文管理
为了避免打开文件后忘记关闭,可以通过管理上下文,即:
with open('a.txt','r') as read_f,open('b.txt','w') as write_f: data=read_f.read() write_f.write(data)
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
with open('log1') as obj1, open('log2') as obj2: pass
2.7 文件的修改
import os with open('a.txt','r',encoding='utf-8') as read_f,\ open('.a.txt.swap','w',encoding='utf-8') as write_f: for line in read_f: if line.startswith('hello'): line='哈哈哈\n' write_f.write(line) os.remove('a.txt') os.rename('.a.txt.swap','a.txt')
2.8 示例:修改配置文件
global log 127.0.0.1 local2 daemon maxconn 256 log 127.0.0.1 local2 info defaults log global mode http timeout connect 5000ms timeout client 50000ms timeout server 50000ms option dontlognull listen stats :8888 stats enable stats uri /admin stats auth admin:1234 frontend oldboy.org bind 0.0.0.0:80 option httplog option httpclose option forwardfor log global acl www hdr_reg(host) -i www.oldboy.org use_backend www.oldboy.org if www backend www.oldboy.org server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
1、查 输入:www.oldboy.org 获取当前backend下的所有记录 2、新建 输入: arg = { 'bakend': 'www.oldboy.org', 'record':{ 'server': '100.1.7.9', 'weight': 20, 'maxconn': 30 } } 3、删除 输入: arg = { 'bakend': 'www.oldboy.org', 'record':{ 'server': '100.1.7.9', 'weight': 20, 'maxconn': 30 } }
#!/usr/bin/env python # -*- coding:utf-8 -*- import json import os def fetch(backend): backend_title = 'backend %s' % backend record_list = [] with open('ha') as obj: flag = False for line in obj: line = line.strip() if line == backend_title: flag = True continue if flag and line.startswith('backend'): flag = False break if flag and line: record_list.append(line) return record_list def add(dict_info): backend = dict_info.get('backend') record_list = fetch(backend) backend_title = "backend %s" % backend current_record = "server %s %s weight %d maxconn %d" % (dict_info['record']['server'], dict_info['record']['server'], dict_info['record']['weight'], dict_info['record']['maxconn']) if not record_list: record_list.append(backend_title) record_list.append(current_record) with open('ha') as read_file, open('ha.new', 'w') as write_file: flag = False for line in read_file: write_file.write(line) for i in record_list: if i.startswith('backend'): write_file.write(i+'\n') else: write_file.write("%s%s\n" % (8*" ", i)) else: record_list.insert(0, backend_title) if current_record not in record_list: record_list.append(current_record) with open('ha') as read_file, open('ha.new', 'w') as write_file: flag = False has_write = False for line in read_file: line_strip = line.strip() if line_strip == backend_title: flag = True continue if flag and line_strip.startswith('backend'): flag = False if not flag: write_file.write(line) else: if not has_write: for i in record_list: if i.startswith('backend'): write_file.write(i+'\n') else: write_file.write("%s%s\n" % (8*" ", i)) has_write = True os.rename('ha','ha.bak') os.rename('ha.new','ha') def remove(dict_info): backend = dict_info.get('backend') record_list = fetch(backend) backend_title = "backend %s" % backend current_record = "server %s %s weight %d maxconn %d" % (dict_info['record']['server'], dict_info['record']['server'], dict_info['record']['weight'], dict_info['record']['maxconn']) if not record_list: return else: if current_record not in record_list: return else: del record_list[record_list.index(current_record)] if len(record_list) > 0: record_list.insert(0, backend_title) with open('ha') as read_file, open('ha.new', 'w') as write_file: flag = False has_write = False for line in read_file: line_strip = line.strip() if line_strip == backend_title: flag = True continue if flag and line_strip.startswith('backend'): flag = False if not flag: write_file.write(line) else: if not has_write: for i in record_list: if i.startswith('backend'): write_file.write(i+'\n') else: write_file.write("%s%s\n" % (8*" ", i)) has_write = True os.rename('ha','ha.bak') os.rename('ha.new','ha') if __name__ == '__main__': """ print '1、获取;2、添加;3、删除' num = raw_input('请输入序号:') data = raw_input('请输入内容:') if num == '1': fetch(data) else: dict_data = json.loads(data) if num == '2': add(dict_data) elif num == '3': remove(dict_data) else: pass """ #data = "www.oldboy.org" #fetch(data) #data = '{"backend": "tettst.oldboy.org","record":{"server": "100.1.7.90","weight": 20,"maxconn": 30}}' #dict_data = json.loads(data) #add(dict_data) #remove(dict_data)

浙公网安备 33010602011771号