如果把静悄悄的革命读书心得得写在了W的文件里,怎么转发在群里

Python读写文件1.open使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。
file_object = open('thefile.txt')try:&&&& all_the_text = file_object.read( )finally:&&&& file_object.close( )
注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法。
2.读文件读文本文件input = open('data', 'r')#第二个参数默认为rinput = open('data')
读二进制文件input = open('data', 'rb')&
读取所有内容file_object = open('thefile.txt')try:&&&& all_the_text = file_object.read( )finally:&&&& file_object.close( )&
读固定字节file_object = open('abinfile', 'rb')try:&&& while True:&&&&&&&& chunk = file_object.read(100)&&&&&&& if not chunk:&&&&&&&&&&& break&&&&&&&& do_something_with(chunk)finally:&&&& file_object.close( )&
读每行list_of_all_the_lines = file_object.readlines( )
如果文件是文本文件,还可以直接遍历文件对象获取每行:
for line in file_object:&&&& process line&
3.写文件写文本文件output = open('data', 'w')&
写二进制文件output = open('data', 'wb')&
追加写文件output = open('data', 'w+')&
写数据file_object = open('thefile.txt', 'w')file_object.write(all_the_text)file_object.close( )&
写入多行file_object.writelines(list_of_text_strings)
注意,调用writelines写入多行在性能上会比使用write一次性写入要高。
在处理日志文件的时候,常常会遇到这样的情况:日志文件巨大,不可能一次性把整个文件读入到内存中进行处理,例如需要在一台物理内存为 2GB 的机器上处理一个 2GB 的日志文件,我们可能希望每次只处理其中 200MB 的内容。在 Python 中,内置的 File 对象直接提供了一个 readlines(sizehint) 函数来完成这样的事情。以下面的代码为例:
file = open('test.log', 'r')sizehint = && # 200Mposition = 0lines = file.readlines(sizehint)while not file.tell() - position & 0:&&&&&& position = file.tell()&&&&&& lines = file.readlines(sizehint)
每次调用 readlines(sizehint) 函数,会返回大约 200MB 的数据,而且所返回的必然都是完整的行数据,大多数情况下,返回的数据的字节数会稍微比 sizehint 指定的值大一点(除最后一次调用 readlines(sizehint) 函数的时候)。通常情况下,Python 会自动将用户指定的 sizehint 的值调整成内部缓存大小的整数倍。
file在python是一个特殊的类型,它用于在python程序中对外部的文件进行操作。在python中一切都是对象,file也不例外,file有file的方法和属性。下面先来看如何创建一个file对象:
file(name[, mode[, buffering]]) file()函数用于创建一个file对象,它有一个别名叫open(),可能更形象一些,它们是内置函数。来看看它的参数。它参数都是以字符串的形式传递的。name是文件的名字。mode是打开的模式,可选的值为r w a U,分别代表读(默认) 写 添加支持各种换行符的模式。用w或a模式打开文件的话,如果文件不存在,那么就自动创建。此外,用w模式打开一个已经存在的文件时,原有文件的内容会被清空,因为一开始文件的操作的标记是在文件的开头的,这时候进行写操作,无疑会把原有的内容给抹掉。由于历史的原因,换行符在不同的系统中有不同模式,比如在 unix中是一个\n,而在windows中是&\r\n&,用U模式打开文件,就是支持所有的换行模式,也就说&\r& '\n' '\r\n'都可表示换行,会有一个tuple用来存贮这个文件中用到过的换行符。不过,虽说换行有多种模式,读到python中统一用\n代替。在模式字符的后面,还可以加上+ b t这两种标识,分别表示可以对文件同时进行读写操作和用二进制模式、文本模式(默认)打开文件。buffering如果为0表示不进行缓冲;如果为1表示进行&行缓冲&;如果是一个大于1的数表示缓冲区的大小,应该是以字节为单位的。
file对象有自己的属性和方法。先来看看file的属性。
closed #标记文件是否已经关闭,由close()改写 encoding #文件编码 mode #打开模式 name #文件名 newlines #文件中用到的换行模式,是一个tuple softspace #boolean型,一般为0,据说用于print
file的读写方法:
F.read([size]) #size为读取的长度,以byte为单位 F.readline([size]) #读一行,如果定义了size,有可能返回的只是一行的一部分 F.readlines([size]) #把文件每一行作为一个list的一个成员,并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数,size是表示读取内容的总长,也就是说可能只读到文件的一部分。 F.write(str) #把str写到文件中,write()并不会在str后加上一个换行符 F.writelines(seq) #把seq的内容全部写到文件中。这个函数也只是忠实地写入,不会在每行后面加上任何东西。 file的其他方法:
F.close() #关闭文件。python会在一个文件不用后自动关闭文件,不过这一功能没有保证,最好还是养成自己关闭的习惯。如果一个文件在关闭后还对其进行操作会产生ValueError F.flush() #把缓冲区的内容写入硬盘 F.fileno() #返回一个长整型的&文件标签& F.isatty() #文件是否是一个终端设备文件(unix系统中的) F.tell() #返回文件操作标记的当前位置,以文件的开头为原点 F.next() #返回下一行,并将文件操作标记位移到下一行。把一个file用于for ... in file这样的语句时,就是调用next()函数来实现遍历的。 F.seek(offset[,whence]) #将文件打操作标记移到offset的位置。这个offset一般是相对于文件的开头来计算的,一般为正数。但如果提供了whence参数就不一定了,whence可以为0表示从头开始计算,1表示以当前位置为原点计算。2表示以文件末尾为原点进行计算。需要注意,如果文件以a或a+的模式打开,每次进行写操作时,文件操作标记会自动返回到文件末尾。 F.truncate([size]) #把文件裁成规定的大小,默认的是裁到当前文件操作标记的位置。如果size比文件的大小还要大,依据系统的不同可能是不改变文件,也可能是用0把文件补到相应的大小,也可能是以一些随机的内容加上去。
#! /usr/bin/pythonimport os,systry:
fsock = open("D:/SVNtest/test.py", "r")except IOError:
print "The file don't exist, Please double check!"
exit()print 'The file mode is ',fsock.modeprint 'The file name is ',fsock.nameP = fsock.tell()print 'the postion is %d' %(P)fsock.close()#Read filefsock = open("D:/SVNtest/test.py", "r")AllLines = fsock.readlines()#Method 1for EachLine in fsock:
print EachLine#Method 2print 'Star'+'='*30for EachLine in AllLines:
print EachLineprint 'End'+'='*30fsock.close()#write this filefsock = open("D:/SVNtest/test.py", "a")fsock.write("""#Line 1 Just for test purpose#Line 2 Just for test purpose#Line 3 Just for test purpose""")fsock.close()#check the file statusS1 = fsock.closedif True == S1:
print 'the file is closed'else:
print 'The file donot close'
本文来自CSDN博客,转载请标明出处:
阅读(...) 评论()10436人阅读
Python(17)
JSON-是一个轻量级的数据交换格式。&JSON维基百科:
关于json的官方文档:
本文由@(Blog地址:)原创。不定期更新,有错误请指正。
Sina微博关注:&
如果这篇博文对您有帮助,为了好的网络环境,不建议转载,建议收藏!如果您一定要转载,请带上后缀和本文地址。
& & & &&dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, sort_keys=False, **kw)
& & & & Serialize ``obj`` as a JSON formatted stream to ``fp`` (a&``.write()``-supporting file-like object).
& & & & # 序列化obj为JSON格式的流写入fp(file-like object)。
& & & & If ``skipkeys`` is true then ``dict`` keys that are not basic types&(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)&will be skipped instead of raising a ``TypeError``.
& & & & skipkeys为真时,dict的keys不是基础类型(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)的一种则不会抛出TypeError`异常,而是被忽略!
&&& a = {&中国&: 1, &china&: 11, &北京天安门&: 111, (&tuple&,): 1111}
&&& json.dumps(a)
Traceback (most recent call last):
File &&pyshell#67&&, line 1, in &module&
json.dumps(a)
File &C:\Python27\lib\json\__init__.py&, line 243, in dumps
return _default_encoder.encode(obj)
File &C:\Python27\lib\json\encoder.py&, line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File &C:\Python27\lib\json\encoder.py&, line 270, in iterencode
return _iterencode(o, 0)
TypeError: keys must be a string
&&& print json.dumps(a, skipkeys = True, ensure_ascii = False, encoding = &gb2312&)
{&北京天安门&: 111, &中国&: 1, &china&: 11}
&&& & & & & &【备注:很多人都不知道怎么打印有中文的字典,上面就是活生生的例子。不单独编码是打印不出来的。除非自己写个方法,但是有json为什么不用呢?】
& & If ``ensure_ascii`` is true (the default), all non-ASCII characters in the&output are escaped with ``\uXXXX`` sequences, and the result is a ``str``&instance consisting of ASCII characters only. &If ``ensure_ascii`` is&``False``, some chunks written
to ``fp`` may be ``unicode`` instances.&This usually happens because the input contains unicode strings or the&``encoding`` parameter is used. Unless ``fp.write()`` explicitly&understands ``unicode`` (as in ``codecs.getwriter``) this is likely to&cause an
& & & &&ensure_ascii为真(默认)时:所有在输出中的非ASCII字符都将转为ascii字符(也就是说结果是1个只包含ASCII字符的str实例),如果不能正确转码(中文之类的)则抛出异常!
& & & & ensure_ascii为假时:一些写入fp的块可能为Unicode实例。这通常是因为输入包含Unicode字符串或编码参数设置所致。除非“fp.write()清楚地知道这是Unicode字符串(如同codecs.getwriter),否则可能会导致错误。
&&& a = {u&中国&: 1, &china&: 11}
&&& json.dumps(a)
'{&\\u00d6\\u00d0\\u00b9\\u00fa&: 1, &china&: 11}'
&&& a = {&中国&: 1, &china&: 11}
&&& json.dumps(a)
Traceback (most recent call last):
File &&pyshell#35&&, line 1, in &module&
json.dumps(a)
File &C:\Python27\lib\json\__init__.py&, line 243, in dumps
return _default_encoder.encode(obj)
File &C:\Python27\lib\json\encoder.py&, line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File &C:\Python27\lib\json\encoder.py&, line 270, in iterencode
return _iterencode(o, 0)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xd6 in position 0: invalid continuation byte
&&& json.dumps(a, encoding = &gb2312&)
'{&\\u4e2d\\u56fd&: 1, &china&: 11}'
& & & & If ``check_circular`` is false, then the circular reference check&for container types will be skipped and a circular reference will&result in an ``OverflowError`` (or worse).
& & & &&check_circular为false时:循环引用检查容器类型将被跳过,循环引用将导致一个overflowerror异常(或更糟)。
& & & & If ``allow_nan`` is false, then it will be a ``ValueError`` to&serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)&in strict compliance of the JSON specification, instead of using the&JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
& & & &&allow_nan为false时:【暂不理解】
& & & & If ``indent`` is a non-negative integer, then JSON array elements and& object members will be pretty-printed with that indent level. An indent&level of 0 will only insert newlines. ``None`` is the most compact&representation. &Since the default item
separator is ``', '``, &the&output might include trailing whitespace when ``indent`` is specified.&You can use ``separators=(',', ': ')`` to avoid this.
& & & & indent:格式化输出!默认None为最紧凑的格式。只能为非负整数,设置为0的时候为换行!和separators结合起来使用!
& & & & If ``separators`` is an ``(item_separator, dict_separator)`` tuple&then it will be used instead of the default ``(', ', ': ')`` separators.&``(',', ':')`` is the most compact JSON representation.
&&& a = {&中国&: 1, &china&: 11, &北京天安门&: 111}
&&& print json.dumps(a, ensure_ascii = False, encoding = &gb2312&, indent = None)
{&北京天安门&: 111, &中国&: 1, &china&: 11}
&&& print json.dumps(a, ensure_ascii = False, encoding = &gb2312&, indent = 0)
&北京天安门&: 111,
&中国&: 1,
&china&: 11
&&& print json.dumps(a, ensure_ascii = False, encoding = &gb2312&, indent = 4)
&北京天安门&: 111,
&中国&: 1,
&china&: 11
&&& print json.dumps(a, ensure_ascii = False, encoding = &gb2312&, indent = 4, separators = (',',':'))
&北京天安门&:111,
&china&:11
&&& & & & & &separators 压缩数据!
&&& len(json.dumps(a, ensure_ascii = False, encoding = &gb2312&, indent = 4, separators = None))
&&& len(json.dumps(a, ensure_ascii = False, encoding = &gb2312&, indent = 4, separators = (',',':')))
& & & & &``encoding`` is the character encoding for str instances, default is UTF-8.
& & & & 编码!上面有演示!
& & & & ``default(obj)`` is a function that should return a serializable version& of obj or raise TypeError. The default simply raises TypeError.
& & & & default(obj)是一个应该返回obj序列化版本的函数or抛出TypeError异常。默认None为简单地抛出异常。也就是把任意不能序列化的对象写个函数变为可序列化为JSON的对象。【PS:暂时还用不上,后续更新】
& & & & If *sort_keys* is ``True`` (default: ``False``), then the output of&dictionaries will be sorted by key.
& & & & 字典排序!默认是False(不排序)。
& & & & To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the&``.default()`` method to serialize additional types), specify it with&&the ``cls`` otherwise ``JSONEncoder`` is used.
& & dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, sort_keys=False, **kw)
& & & & Serialize ``obj`` to a JSON formatted ``str``.
& & & & 序列化obj为一个json字符串!
& & load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
& & & & Deserialize ``fp`` (a ``.read()``-supporting file-like object containing&a JSON document) to a Python object.
& & & & # 反序列化fp(&包含JSON结构的file-like object)为Python对象!
& & & & If the contents of ``fp`` is encoded with an ASCII based encoding other&than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must&be specified. Encodings that are not ASCII based (such as UCS-2) are&not allowed, and should be wrapped with&``codecs.getreader(fp)(encoding)``,
or simply decoded to a ``unicode``&object and passed to ``loads()``
& & & &&如果fp的内容是基于ASCII编码而不是UTF-8(如latin-1)则必须指定encoding的名字,。编码是不允许不是基于ASCII编码的(如UCS-2),而应该用`codecs.getreader(fp)(encoding),或简单地解码为Unicode对象传递给loads()。&
& & & & ``object_hook`` is an optional function that will be called with the&result of any object literal decode (a ``dict``). The return value of&&``object_hook`` will be used instead of the ``dict``. This feature&can be used to implement custom decoders (e.g.
JSON-RPC class hinting).
& & & &object_hook&是将要被一些对象逐字解码(一个dict)的结果调用的一个可选的函数。object_hook的返回值将用来代替dict。将来可以使用此功能来实现自定义解码器。
& & & & ``object_pairs_hook`` is an optional function that will be called with the&result of any object literal decoded with an ordered list of pairs. &The&return value of ``object_pairs_hook`` will be used instead of the ``dict``.&This feature can be used
to implement custom decoders that rely on the&order that the key and value pairs are decoded (for example,&collections.OrderedDict will remember the order of insertion). If&``object_hook`` is also defined, the ``object_pairs_hook`` takes priority.
& & & &&object_pairs_hook
& & loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
& & & & Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON&document) to a Python object.
& & & & 反序列化s(一个JSON标准的str或者unicode实例)为Python对象。
& & & & If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding&other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name&must be specified. Encodings that are not ASCII based (such as UCS-2)&&are not allowed and should be decoded
to ``unicode`` first.
& & & &&如果s是一个str实例并且是基于ASCII编码而不是utf-8编码,则必须指定encoding的名字。&编码是不允许不是基于ASCII编码的(如UCS-2),并且首先解码为unicode& & &&
& & & & ``parse_float``, if specified, will be called with the string&of every JSON float to be decoded. By default this is equivalent to&float(num_str). This can be used to use another datatype or parser&for JSON floats (e.g. decimal.Decimal).
& & & & ``parse_int``, if specified, will be called with the string&of every JSON int to be decoded. By default this is equivalent to&int(num_str). This can be used to use another datatype or parser&for JSON integers (e.g. float).
& & & & ``parse_constant``, if specified, will be called with one of the&following strings: -Infinity, Infinity, NaN, null, true, false.&This can be used to raise an exception if invalid JSON numbers&are encountered.
JSON常见操作--dict、str相互转化
&&& d = {&a&: 1, &b&: 2, &c&: 3}
&&& import json
&&& str_d = json.dumps(d)
&&& print str_d, type(str_d)
{&a&: 1, &c&: 3, &b&: 2} &type 'str'&
&&& d_trans = json.loads(str_d)
&&& print d_trans, type(d_trans)
{u'a': 1, u'c': 3, u'b': 2} &type 'dict'&
&&& json.dumps()方法的功能是把Python对象变为JSON字符串。loads()反序列化JSON字符串为相应的Python对象。对应为下图:
JSON &--& Python object:
&&& d = {&a&: 1, &c&: 3, &b&: 2}
&&& import json
&&& with open(&C:\\Users\\admin\\Desktop\\111.txt&, &w&) as f:
json.dump(d, f)
&&& dump()方法的功能是把Python object写入到文件!注意到我们是写进一个file-like object而不是一个地址!load()对应为读取!
&&& with open(&C:\\Users\\admin\\Desktop\\111.txt&, &r&) as f:
d1 = json.load(f)
{u'a': 1, u'c': 3, u'b': 2}
&&& 题外:
with as语句的妙用:避免打开文件后手写关闭文件代码,避免人为忘记写f.close(),避免使用try--except--finally导致的大量代码!
1、为什么使用JSON:因为这是一种JSON是一种数据交换格式,意味着可以被N多语言读取;可以存在本地,避免数据多次处理;还可以通过socket和网络上其他计算机交换数据【这应用更科学】!
2、Python序列化模块为pickle和Cpickle,方法和JSON差不多!但我推荐使用JSON!
本文由@(Blog地址:)原创。不定期更新,有错误请指正。
Sina微博关注:&
如果这篇博文对您有帮助,为了好的网络环境,不建议转载,建议收藏!如果您一定要转载,请带上后缀和本文地址。
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:97511次
积分:1379
积分:1379
排名:千里之外
原创:39篇
评论:46条
(2)(1)(8)(5)(11)(6)(2)(5)25288人阅读
& & & 在我们的程序设计中经常需要对一些参数进行配置,配置好后还要在下一次启动仍然有效,那么一个有效的可行办法就是使用ini文件,也就是Windows初始化文件来保存一些我们的设置,然后让程序启动的时候从这个ini文件中读取相关配置。我们需要做以下的工作。
& & & 1.创建此ini文件,Windows对ini文件的操作有专门的函数,我们经常用的就是WritePrivateProfileString()和GetPrivateProfileString()了。那么我们在程序的初始化时首先检查是否存在ini文件,如果不存在则创建一个默认的ini文件。
& & & & & 我们使用CFileFind类查找我们需要的ini文件是否存在,若不存在则创建一个。WritePrivateProfileString()当ini不存在时会自动创建一个ini文件在指定路径。
//向D盘写入程序数据库连接ini文件信息,默认设置如下
//查找是否存在ini文件,若不存在,则生成一个新的默认设置的ini文件,这样就保证了我们更改后的设置每次都可用
BOOL ifFind = finder.FindFile(_T(&d:\\RoadDataManagerApp.ini&));
if( !ifFind )
::WritePrivateProfileStringW(_T(&Database connection Info&),_T(&IP&),_T(&10.210.0.9&),_T(&d:\\RoadDataManagerApp.ini&));
::WritePrivateProfileStringW(_T(&Database connection Info&),_T(&Database&),_T(&RoadNetData&),_T(&d:\\RoadDataManagerApp.ini&));
::WritePrivateProfileStringW(_T(&Database connection Info&),_T(&UID&),_T(&sa&),_T(&d:\\RoadDataManagerApp.ini&));
::WritePrivateProfileStringW(_T(&Database connection Info&),_T(&PWD&),_T(&4814278&),_T(&d:\\RoadDataManagerApp.ini&));
& & & &2.在刚才创建的ini文件中赋值,也就是WritePrivateProfileString()中所做的。
& & & &3.在需要用到ini文件的地方从ini文件中读取数据。例如:
::GetPrivateProfileStringW(_T(&Database connection Info&),_T(&IP&),_T(&没找到IP信息&),m_strCurrentIP.GetBuffer(MAX_PATH),MAX_PATH,_T(&d:\\RoadDataManagerApp.ini&));
::GetPrivateProfileStringW(_T(&Database connection Info&),_T(&Database&),_T(&没找到数据库名信息&),m_strCurrentDBName.GetBuffer(MAX_PATH),MAX_PATH,_T(&d:\\RoadDataManagerApp.ini&));
::GetPrivateProfileStringW(_T(&Database connection Info&),_T(&UID&),_T(&没找到用户名信息&),m_strCurrentUID.GetBuffer(MAX_PATH),MAX_PATH,_T(&d:\\RoadDataManagerApp.ini&));
::GetPrivateProfileStringW(_T(&Database connection Info&),_T(&PWD&),_T(&没找到用户密码信息&),m_strCurrentPWD.GetBuffer(MAX_PATH),MAX_PATH,_T(&d:\\RoadDataManagerApp.ini&));
//在这里必须ReleaseBuffer(),否则无法再后面进行字符串的连接
m_strCurrentIP.ReleaseBuffer();
m_strCurrentDBName.ReleaseBuffer();
m_strCurrentUID.ReleaseBuffer();
m_strCurrentPWD.ReleaseBuffer();
& & & & & &这样基本的操作我们就都知道了。下面详细说明对ini文件的各种操作。
INI文件简介
在我们写程序时,总有一些配置信息需要保存下来,以便在下一次启动程序完成初始化,这实际上是一种类持久化。将一些信息写入INI文件(initialization file)中,可完成简单的持久化支持。
Windows提供了API接口用于操作INI文件,其支持的INI文件格式一般如下:
===============================
[Section1]
Key11=value11
Key12=value12
[Section2]
Key21=value21
Key22=value22
[SectionN]
KeyN1=valueN1
KeyN2=valueN2
===============================
一般一个INI文件可有N个节,每节可有n个键名及值对应,每个键名及其值以等式形式占一行。
一般键的名称可任取,不过建议用有意义的字符及词构成。值一般可为整数和字符串,其它类型要进行转换。
常见的系统配置文件:
C:/boot.ini
C:/WINDOWS/win.ini
C:/WINDOWS/system.ini
C:/WINDOWS/desktop.ini
C:/WINDOWS/Resources/Themes/Windows Classic.theme
注意,字符串存贮在INI文件中时没有引号;key和value之间的等号前后不容空格;注释以分号“;”开头。
VC中操作INI文件的API
(1)操作系统配置文件Win.ini的函数:
GetProfileSection
读取win.ini中指定节lpAppName中所有键名及其值。lpReturnedString字符串形式如下:
Key1=Value1/0Key2=Value2/0…KeyN=ValueN/0/0
GetProfileString
读取win.ini中指定节lpAppName中键名为lpKeyName对应变量的字符串值。
GetProfileInt
读取win.ini中指定节lpAppName中键名为lpKeyName对应变量的整数值。
WriteProfileSection
写(替换)win.ini中指定节lpAppName中的键值。
lpString字符串形式同GetProfileSection中的lpReturnedString。
WriteProfileString
写(替换)win.ini中指定节lpAppName中键名为lpKeyName对应变量的字符串值。
&(2)操作用户自定义配置文件(PrivateProfile.ini)的函数:
GetPrivateProfileSectionNames
读取lpFileName指定的配置文件中所有的节名。lpszReturnBuffer字符串形式如下:
Section1/0Section2/0…SectionN/0/0
GetPrivateProfileSection
同GetProfileSection。
GetPrivateProfileString
同GetProfileString。
GetPrivateProfileInt&&&&&
同GetProfileInt
GetPrivateProfileStruct
须同WritePrivateProfileStruct配套使用。
WritePrivateProfileSection
同WriteProfileSection
WritePrivateProfileString
同WriteProfileString
WritePrivateProfileStruct
(1)使用得最频繁的是 GetPrivateProfileString 和 WritePrivateProfileString,没有WriteProfileInt/WritePrivateProfileInt函数。
(2)Get系列读取节键值,如果文件路径有误或节键名不对则返回设定的默认值。
(3)访存自定义配置文件时,文件路径lpFileName必须完整,文件名前面的各级目录必须存在。如果lpFileName文件路径不存在,则函数返回FALSE,GetLastError() = ERROR_PATH_NOT_FOUND。如果路径正确,但是文件不存在,则该函数将先创建该文件。如果路径及文件存在,则在现有ini文件基础上进行读写。
如果 lpFileName 只指定文件名而没有路径的话,调用API将会去 Windows 的安装目录去查找而不会在当前目录查找。
(4)要对调用API的模块(exe)所在目录下进行配置文件操作,可使用形如“.//config.ini”的相对路径,注意转义符。
(5)调用WritePrivateProfileSection,若参数三&lpString为NULL,则可将对应section的全部内容清空;调用WritePrivateProfileString,若参数三&lpString为NULL,则可将对应key删除。
跨平台配置文件
INI文件本质是对文件和字符串的处理,因此在跨平台项目中的配置文件可以基于&stdio.h&中的标C文件FILE,然后实现像类似以上对节([Section])、键(Key)和值(Value)的字符串读写功能。
鉴于XML的树形描述层次结构性清晰,现在很多软件都大面积使用XML文件进行配置,如QQ的全局配置文件C:/Program Files/Tencent/QQ/gf-config.xml。java程序的配置文件基本都使用XML格式,C++中并没有操作XML文件的标准库。
在C/C++程序中要使用XML做为配置文件,涉及到XML的解析。Windows平台可使用MsXml对XML进行解析,参考《》,跨平台可以考虑自己实现,或使用C++ BOOST正则表达式,或选择,如、、、等。
CIniFile类
&&&&以下提供对Windows操作INI文件的API的简单封装类CIniFile。
在VC++中读写INI文件
  在我们写的程序当中,总有一些配置信息需要保存下来,以便完成程序的功能,最简单的办法就是将这些信息写入INI文件中,程序初始化时再读入.具体应用如下:
  一.将信息写入.INI文件中.
  1.所用的WINAPI函数原型为:&
BOOL WritePrivateProfileString(
LPCTSTR lpAppName,
LPCTSTR lpKeyName,
LPCTSTR lpString,
LPCTSTR lpFileName
  其中各参数的意义:
   LPCTSTR lpAppName 是INI文件中的一个字段名.
   LPCTSTR lpKeyName 是lpAppName下的一个键名,通俗讲就是变量名.
   LPCTSTR lpString 是键值,也就是变量的值,不过必须为LPCTSTR型或CString型的.
   LPCTSTR lpFileName 是完整的INI文件名.
  2.具体使用方法:设现有一名学生,需把他的姓名和年龄写入 c:\stud\student.ini 文件中.&
CString strName,strT
strName=&张三&;
::WritePrivateProfileString(&StudentInfo&,&Name&,strName,&c:\\stud\\student.ini&);
  此时c:\stud\student.ini文件中的内容如下:
   [StudentInfo]
   Name=张三
  3.要将学生的年龄保存下来,只需将整型的值变为字符型即可:
strTemp.Format(&%d&,nAge);
::WritePrivateProfileString(&StudentInfo&,&Age&,strTemp,&c:\\stud\\student.ini&);
 二.将信息从INI文件中读入程序中的变量.
  1.所用的WINAPI函数原型为:
DWORD GetPrivateProfileString(
LPCTSTR lpAppName,&
LPCTSTR lpKeyName,&
LPCTSTR lpDefault,&
LPTSTR lpReturnedString,&
DWORD nSize,&
LPCTSTR lpFileName&
  其中各参数的意义:&
   前二个参数与 WritePrivateProfileString中的意义一样.
   lpDefault : 如果INI文件中没有前两个参数指定的字段名或键名,则将此值赋给变量.&
   lpReturnedString : 接收INI文件中的值的CString对象,即目的缓存器.
   nSize : 目的缓存器的大小.
   lpFileName : 是完整的INI文件名.
  2.具体使用方法:现要将上一步中写入的学生的信息读入程序中.
CString strStudN
int nStudA&
GetPrivateProfileString(&StudentInfo&,&Name&,&默认姓名&,strStudName.GetBuffer(MAX_PATH),MAX_PATH,&c:\\stud\\student.ini&);
  执行后 strStudName 的值为:&张三&,若前两个参数有误,其值为:&默认姓名&.
  3.读入整型值要用另一个WINAPI函数:&
UINT GetPrivateProfileInt(
LPCTSTR lpAppName,&
LPCTSTR lpKeyName,&
INT nDefault,&
LPCTSTR lpFileName&
  这里的参数意义与上相同.使用方法如下:
nStudAge=GetPrivateProfileInt(&StudentInfo&,&Age&,10,&c:\\stud\\student.ini&);
 三.循环写入多个值,设现有一程序,要将最近使用的几个文件名保存下来,具体程序如下:
  1.写入:
CString strTemp,strTempA;
int nCount=6;
file://共有6个文件名需要保存
for(i=0;i {strTemp.Format(&%d&,i);
strTempA=文件名;
file://文件名可以从数组,列表框等处取得.
::WritePrivateProfileString(&UseFileName&,&FileName&+strTemp,strTempA,
&c:\\usefile\\usefile.ini&);
strTemp.Format(&%d&,nCount);
::WritePrivateProfileString(&FileCount&,&Count&,strTemp,&c:\\usefile\\usefile.ini&);
file://将文件总数写入,以便读出.
  2.读出:
nCount=::GetPrivateProfileInt(&FileCount&,&Count&,0,&c:\\usefile\\usefile.ini&);
for(i=0;i {strTemp.Format(&%d&,i);
strTemp=&FileName&+strT
::GetPrivateProfileString(&CurrentIni&,strTemp,&default.fil&, strTempA.GetBuffer(MAX_PATH),MAX_PATH,&c:\\usefile\\usefile.ini&);
file://使用strTempA中的内容.
  补充四点:
   1.INI文件的路径必须完整,文件名前面的各级目录必须存在,否则写入不成功,该函数返回 FALSE 值.
   2.文件名的路径中必须为 \\ ,因为在VC++中, \\ 才表示一个 \ .
   3.也可将INI文件放在程序所在目录,此时 lpFileName 参数为: &.\\student.ini&.
   4.从网页中粘贴源代码时,最好先粘贴至记事本中,再往VC中粘贴,否则易造成编译错误,开始时我也十分不解,好好的代码怎么就不对呢?后来才找到这个方法.还有一些代码中使用了全角字符如:<,\等,也会
造成编译错误.
============
VC中用函数读写ini文件的方法
&&&&&&&& ini文件(即Initialization file),这种类型的文件中通常存放的是一个程序的初始化信息。ini文件由若干个节(Section)组成,每个Section由若干键(Key)组成,每个Key可以赋相应的值。读写ini文件实际上就是读写某个的Section中相应的Key的值,而这只要借助几个函数即可完成。
一、向ini文件中写入信息的函数
1. 把信息写入系统的win.ini文件
BOOL WriteProfileString(
&&&&& LPCTSTR lpAppName, // 节的名字,是一个以0结束的字符串
&&&&& LPCTSTR lpKeyName, // 键的名字,是一个以0结束的字符串。若为NULL,则删除整个节
&&&&& LPCTSTR lpString&&&&&& // 键的值,是一个以0结束的字符串。若为NULL,则删除对应的键
2. 把信息写入自己定义的.ini文件
BOOL WritePrivateProfileString(
&&&&& LPCTSTR lpAppName,&&&&& // 同上
&&&&& LPCTSTR lpKeyName,&&&&& // 同上
&&&&& LPCTSTR lpString,&&&&&& // 同上
&&&&& LPCTSTR lpFileName&&&&& // 要写入的文件的文件名。若该ini文件与程序在同一个目录下,也可使用相对
&&&&&&&&&&& //路径,否则需要给出绝度路径。
::WriteProfileString(&Test&,&id&,&xym&);&
//在win.ini中创建一个Test节,并在该节中创建一个键id,其值为xym
::WritePrivateProfileString(&Test&,&id&,&xym&,&d://vc//Ex1//ex1.ini&);
//在Ex1目录下的ex1.ini中创建一个Test节,并在该节中创建一个键id,其值为xym
//若Ex1.ini文件与读写该文件的程序在同一个目录下,则上面语句也可写为:
::WritePrivateProfileString(&Test&,&id&,&xym&,&.//ex1.ini&);
需要注意的是,C系列的语言中,转义字符'//'表示反斜线'/'。另外,当使用相对路径时,//前的.号不能丢掉了。
二、从ini文件中读取数据的函数
1、从系统的win.ini文件中读取信息
(1) 读取字符串
DWORD GetProfileString(
&&&&& LPCTSTR lpAppName,&&&&&&&&&&& // 节名
&&&&& LPCTSTR lpKeyName,&&&&&&&&&&& // 键名,读取该键的值
&&&&& LPCTSTR lpDefault,&&&&&&&&&&& // 若指定的键不存在,该值作为读取的默认值
&&&&& LPTSTR lpReturnedString,&&&&& // 一个指向缓冲区的指针,接收读取的字符串
&&&&& DWORD nSize&&&&&&&&&&&&&&&&&& // 指定lpReturnedString指向的缓冲区的大小
::GetProfileString(&Test&,&id&,&Error&,str.GetBuffer(20),20);
(2) 读取整数
UINT GetProfileInt(
&&&&& LPCTSTR lpAppName,&&&&& // 同上
&&&&& LPCTSTR lpKeyName,&&&&& // 同上
&&&&& INT nDefault&&&&&&&&&&& // 若指定的键名不存在,该值作为读取的默认值
如使用以下语句写入了年龄信息:
::WriteProfileString(&Test&,&age&,&25&);&
//在win.ini中创建一个Test节,并在该节中创建一个键age,其值为25
则可用以下语句读取age键的值:
age=::GetProfileInt(&Test&,&age&,0);
2、从自己的ini文件中读取信息
(1) 读取字符串
DWORD GetPrivateProfileString(
&&&&& LPCTSTR lpAppName,&&&&&&&&&&& // 同1(1)
&&&&& LPCTSTR lpKeyName,&&&&&&&&&&& // 同1(1)
&&&&& LPCTSTR lpDefault,&&&&&&&&&&& // 同1(1)
&&&&& LPTSTR lpReturnedString,&&&&& // 同1(1)
&&&&& DWORD nSize,&&&&&&&&&&&&&&&&& // 同1(1)
&&&&& LPCTSTR lpFileName&&&&&&&&&&& // 读取信息的文件名。若该ini文件与程序在同一个目录下,也可使用相&&&&&&
&&&&&&&&&&& //对路径,否则需要给出绝度路径。
::GetPrivateProfileString(&Test&,&id&,&Error&,str.GetBuffer(20),20,&.//ex1.ini&);
::GetPrivateProfileString(&Test&,&id&,&Error&,str.GetBuffer(20),20,&d://vc//Ex1//ex1.ini&);
(2) 读取整数
UINT GetPrivateProfileInt(
&&&&& LPCTSTR lpAppName,&&&&& // 同上
&&&&& LPCTSTR lpKeyName,&&&&& // 同上
&&&&& INT nDefault,&&&&&&&&&& // 若指定的键名不存在,该值作为读取的默认值
&&&&& LPCTSTR lpFileName&&&&& // 同上
如使用以下语句写入了年龄信息:
::WritePrivateProfileString(&Test&,&age&,&25&,&.//ex1.ini&);&
//在ex1.ini中创建一个Test节,并在该节中创建一个键age,其值为25
则可用以下语句读取age键的值:
age=::GetPrivateProfileInt(&Test&,&age&,0,&.//ex1.ini&);
三、 删除键值或节
&&&&&& 回顾一下WriteProfileString函数的说明
BOOL WriteProfileString(
&&&&& LPCTSTR lpAppName, // 节的名字,是一个以0结束的字符串
&&&&& LPCTSTR lpKeyName, // 键的名字,是一个以0结束的字符串。若为NULL,则删除整个节
&&&&& LPCTSTR lpString&&&&&& // 键的值,是一个以0结束的字符串。若为NULL,则删除对应的键
&&&&&& 由此可见,要删除某个节,只需要将WriteProfileString第二个参数设为NULL即可。而要删除某个键,则只需要将该函数的第三个参数设为 NULL即可。这是删除系统的win.ini中的节或键,类似的,要删除自己定义的ini文件中的节或键,也可做相同的操作。
&&&&&& 如:
::WriteProfileString(&Test&,NULL,NULL);&&&&& //删除win.ini中的Test节
::WriteProfileString(&Test&,&id&,NULL);&&&&& //删除win.ini中的id键
::WritePrivateProfileString(&Test&,NULL,NULL,&.//ex1.ini&);&&&&& //删除ex1.ini中的Test节
::WritePrivateProfileString(&Test&,&id&,NULL,&.//ex1.ini&);&&&&& //删除ex1.ini中的id键
四、如何判断一个ini文件中有多少个节
&&&&&& 要判断一个ini文件中有多少个节,最简单的办法就是将所有的节名都找出来,然后统计节名的个数。而要将所有的节名找出来,使用GetPrivateProfileSectionNames函数就可以了,其原型如下:
DWORD GetPrivateProfileSectionNames(
&&&&& LPTSTR lpszReturnBuffer,&&&&& // 指向一个缓冲区,用来保存返回的所有节名
&&&&& DWORD nSize,&&&&&&&&&&&&&&&&& // 参数lpszReturnBuffer的大小
&&&&& LPCTSTR lpFileName&&&&&&&&&&& // 文件名,若该ini文件与程序在同一个目录下,
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& //也可使用相对路径,否则需要给出绝度路径
下面的是用来统计一个ini文件中共有多少个节的函数,当然,如果需要同时找到每个节中的各个键及其值,根据找到节名就可以很容易的得到了。
/*统计共有多少个节
节名的分离方法:若chSectionNames数组的第一字符是'/0'字符,则表明
有0个节。否则,从chSectionNames数组的第一个字符开始,顺序往后找,
直到找到一个'/0'字符,若该字符的后继字符不是 '/0'字符,则表明前
面的字符组成一个节名。若连续找到两个'/0'字符,则统计结束*/
int CTestDlg::CalcCount(void)
TCHAR&&&&&& chSectionNames[2048]={0};&&&&&& //所有节名组成的字符数组
char * pSectionN //保存找到的某个节名字符串的首地址
&&&&&& //i指向数组chSectionNames的某个位置,从0开始,顺序后移
int j=0;&&&&& //j用来保存下一个节名字符串的首地址相对于当前i的位置偏移量
int count=0;&&&&& //统计节的个数
//char id[20];
::GetPrivateProfileSectionNames(chSectionNames,2048,&.//ex1.ini&);&&&
for(i=0;i&2048;i++,j++)
&&&&& if(chSectionNames[0]=='/0')
&&&&&&&&&&&& //如果第一个字符就是0,则说明ini中一个节也没有
&&&&& if(chSectionNames[i]=='/0')
&&&&&& pSectionName=&chSectionNames[i-j]; //找到一个0,则说明从这个字符往前,减掉j个偏移量,
&&&&&&&&&&& //就是一个节名的首地址
&&&&&& j=-1;&&&&&&&& //找到一个节名后,j的值要还原,以统计下一个节名地址的偏移量
&&&&&&&&&&& //赋成-1是因为节名字符串的最后一个字符0是终止符,不能作为节名
&&&&&&&&&&& //的一部分
&&&&&& /*::GetPrivateProfileString(pSectionName,&id&,&Error&,id,20,&.//ex1.ini&);
&&&&&& name.Format(&%s&,id);*/&&&
&&&&&& //在获取节名的时候可以获取该节中键的值,前提是我们知道该节中有哪些键。
&&&&&& AfxMessageBox(pSectionName);&&&&& //把找到的显示出来
&&&&&& if(chSectionNames[i+1]==0)
&&&&&&&&&&&&& //当两个相邻的字符都是0时,则所有的节名都已找到,循环终止
&&&&& }&&&
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
在VC程序中利用系统提供的GetPrivateProfileString及WritePrivateProfileString函数直接读写系统配置ini文件(指定目录下的Ini文件)
假设在当前目录下有一个文件名为Tets.ini的文件
用于保存用户名和密码
文件格式如下:
[Section1]
Item1=huzhifeng
Item2=1234565
1.写INI文件
void&CINI_File_TestDlg::OnButtonWrite()&
&//&TODO:&Add&your&control&notification&handler&code&here
&CString&strSection&&&&&&&=&&Section1&;
&&CString&strSectionKey&&&&=&&Item1&;
&char&strBuff[256];
&&CString&strValue&&&&&&&=&_T(&&);
&CString&strFileP
&strFilePath=GetCurrentDirectory(256,strBuff);&&//获取当前路径
&strFilePath.Format(&%s//Test.ini&,strBuff);
&GetDlgItemText(IDC_EDIT_NAME,strValue);&&&&&//获取文本框内容:即姓名
&WritePrivateProfileString(strSection,strSectionKey,strValue,strFilePath);&&//写入ini文件中相应字段
&strSectionKey=&Item2&;
&GetDlgItemText(IDC_EDIT_PASSWORD,strValue);&&&//获取文本框内容:即密码
&WritePrivateProfileString(strSection,strSectionKey,strValue,strFilePath);
2.读INI文件内容
void&CINI_File_TestDlg::OnButtonRead()&
&//&TODO:&Add&your&control&notification&handler&code&here
&CString&strSection&&&&&&&=&&Section1&;
&&CString&strSectionKey&&&&=&&Item1&;
&char&strBuff[256];
&CString&strValue&&&&&&&=&_T(&&);
&CString&strFileP
&strFilePath=GetCurrentDirectory(256,strBuff);&&//获取当前路径
&strFilePath.Format(&%s//Test.ini&,strBuff);
&GetPrivateProfileString(strSection,strSectionKey,NULL,strBuff,80,strFilePath);&//读取ini文件中相应字段的内容
&strValue=strB
&SetDlgItemText(IDC_EDIT_NAME,strValue);
&strSectionKey=&Item2&;
&GetPrivateProfileString(strSection,strSectionKey,NULL,strBuff,80,strFilePath);
&strValue=strB
&SetDlgItemText(IDC_EDIT_PASSWORD,strValue);
&UpdateData(FALSE);
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:122873次
积分:1279
积分:1279
排名:千里之外
转载:11篇
评论:27条
(1)(1)(3)(6)(1)(4)(4)

我要回帖

更多关于 教师读书心得体会 的文章

 

随机推荐