https://blog.csdn.net/jiede1/article/details/79064780
1.支持配置文件格式
[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no
首先是由一个sections(如 [DEFAULT] )引起,下面接类似“name = value”形式的key-value对。其实,接 “name : value”的形式也可以。
2.函数API
-read(filename) 直接读取文件内容
-sections() 得到所有的section,并以列表的形式返回
-options(section) 得到该section的所有option
-items(section) 得到该section的所有键值对
-get(section,option) 得到section中option的值,返回为string类型
-getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。
-add_section(section) 添加一个新的section
-set( section, option, value) 对section中的option进行设置
需要调用write将内容写入配置文件。
pip install ConfigParser
https://www.cnblogs.com/wang-yc/p/5620944.html
2https://blog.csdn.net/liuchunming033/article/details/39376147
准备一个文件text.txt,内容为一行"AAAAAAAABBBBBBBBCCCCCCCCDDDDDDDD"。
''' Created on Sep 18, 2014 @author: liu.chunming ''' #There is a text.txt file which contains "AAAAAAAABBBBBBBBCCCCCCCCDDDDDDDD" text_file=r"C:\Users\liu.chunming\Desktop\test.txt" #open() f=open(text_file,"r") #seek() f.seek(8,0) #tell pos=f.tell() #read() text_to_number=f.read(8) f.seek(8,1) text_to_all=f.read() f.close() print pos print text_to_number
结果
8 BBBBBBBB DDDDDDDD
代码分析:
这段代码涉及到文件操作的几个方法。
1.open()方法
用来打开一个文件。这是对文件操作的第一步。open()方法的语法如下:open(name[, mode[,buffering]])。name参数是open方法的唯一强制参数,用来标识要打开的文件名。mode是文件打开的模式,通常有三种:r为读模式打开,w为写模式打开,a为追加模式打开。
2.seek()方法
用它设置当前文件读/写指针的偏移。seek()方法的语法如下:fileObject.seek(offset[, whence])。offset参数指明偏移量,第二个参数指出第一个参数偏移基准是哪里:0 表示移动到一个绝对位置 (从文件开始算起),1 表示移到一个相对位置 (从当前位置算起),还有 2 表示对于文件尾的一个相对位置。”
3.tell()方法
返回当前文件指针的位置。
4.read()方法
读取文件内容的方法。读取文件内容的另外两个方法是readline和readlines。
readline()每次读取一行,当前位置移到下一行;
readlines()读取整个文件所有行,保存在一个列表(list)变量中,每行作为一个元素;
read(size)从文件当前位置起读取size个字节(如果文件结束,就读取到文件结束为止),如果size是负值或省略,读取到文件结束为止,返回结果是一个字符串。
5.close()方法
操作完文件,一定要关闭文件。关闭文件就是用这个close方法