【转】python处理文本文件
2010-06-0111:10:53|分类:Python|标签:pythoncookbook|字号订阅
1.从文件读取文本或数据
一次将文件内容读入一个长字符串的最简便方法
如:all_the_text=open(''thefile.txt'').read()#文本文件的全部文本
all_the_data=open(''abinfile'',''rb'').read()#2进制文件的全部数据
更好的方法是将文件对象和一个变量绑定,可以及时关闭文件。比如,读取文本文件内容:
如:file_object=open(''thefile.txt'')#打开文件
all_the_text=file_object.read()#文本文件的全部文本
file_object.close()#使用完毕,关闭文件
将文本文件的全部内容按照分行作为一个list读出有5种方法:
list_of_all_the_lines=file_object.readlines()#方法1
list_of_all_the_lines=file_object.read().splitlines(1)#方法2
list_of_all_the_lines=file_object.read().splitlines()#方法3
list_of_all_the_lines=file_object.read().split(''\n'')#方法4
list_of_all_the_lines=list(file_object)#方法5
2.文件中写入文本或2进制数据
将一个(大)字符串写入文件的最简单的方法如下:
如:open(''thefile.txt'',''w'').write(all_the_text)#写入文本到文本文件
open(''abinfile'',''wb'').write(all_the_data)#写入数据到2进制文件
更好的方法是将文件对象和一个变量绑定,可以及时关闭文件。比如,文本文件写入内容:
如:file_object=open(''thefile.txt'',''w'')
file_object.write(all_the_text)
file_object.close()
写入文件的内容更多时不是一个大字符串,而是一个字符串的list(或其他序列),这时应该使用writelines方法(此方法同样适用于2进制文件的写操作)
如:file_object.writelines(list_of_text_strings)
open(''abinfile'',''wb'').writelines(list_of_data_strings)
3.读取文件的指定一行
如:importlinecache
#thefiepath文件路径
#desired_line_number整数,文件的特定行
theline=linecache.getline(thefilepath,desired_line_number)
4.需要统计文件的行数
如:count=len(open(thefilepath).readlines())#方法1
count=0#方法2
forlineinopen(thefilepath).xreadlines():count+=1
5.读取INI配置文件
importConfigParser
importstring
_ConfigDefault={
"database.dbms":"mysql",
"database.name":"",
"database.user":"root",
"database.password":"",
"database.host":"127.0.0.1"
}
defLoadConfig(file,config={}):
"""
returnsadictionarywithkeysoftheform
. |
|