设为首页 收藏本站
查看: 1630|回复: 0

[经验分享] 摘自python cookbook2(文本文件)

[复制链接]

尚未签到

发表于 2017-5-3 13:04:23 | 显示全部楼层 |阅读模式
摘自python cookbook2(文本文件)
url:http://wiki.woodpecker.org.cn/moin/PyCookbook

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.读取文件的指定一行
如:import linecache
   #thefiepath             文件路径
   #desired_line_number    整数,文件的特定行
theline = linecache.getline(thefilepath, desired_line_number)

4.需要统计文件的行数
如:count = len(open(thefilepath).readlines(  ))                  #方法1

count = 0                                                      #方法2
for line in open(thefilepath).xreadlines(  ): count += 1


5.读取INI配置文件

import ConfigParser
import string

_ConfigDefault = {
    "database.dbms":            "mysql",
    "database.name":            "",
    "database.user":            "root",
    "database.password":        "",
    "database.host":            "127.0.0.1"
    }

def LoadConfig(file, config={}):
    """
    returns a dictionary with keys of the form
    <section>.<option> and the corresponding values
    """
    #返回一个字典,格式如下: key:     <section>.option>
    #                   value :  对应的值



    config = config.copy(  )
    cp = ConfigParser.ConfigParser(  )
    cp.read(file)
    for sec in cp.sections(  ):
        name = string.lower(sec)
        for opt in cp.options(sec):
            config[name + "." + string.lower(opt)] = string.strip(
                cp.get(sec, opt))
    return config

if _ _name_ _=="_ _main_ _":
    print LoadConfig("some.ini", _ConfigDefault)



6.有ZIP压缩文件, 不需要解压,直接检查其包含的部分或全部文件信息
如:import zipfile
z = zipfile.ZipFile("zipfile.zip", "r")
for filename in z.namelist(  ):
    print 'File:', filename,
    bytes = z.read(filename)
    print 'has',len(bytes),'bytes'

7.分解出文件路径所有组成部分
如:
import os, sys
def splitall(path):
    allparts = []
    while 1:
        parts = os.path.split(path)
        if parts[0] == path:  # sentinel for absolute paths  #绝对路径的哨兵
            allparts.insert(0, parts[0])
            break
        elif parts[1] == path: # sentinel for relative paths #相对路径的哨兵
            allparts.insert(0, parts[1])
            break
        else:                                                #处理其余部分
            path = parts[0]
            allparts.insert(0, parts[1])
    return allparts

8.遍历检查目录, 或者遍历以某目录为根目录的完整的目录树,获取符合特定模式的全部文件
如:
import os.path, fnmatch
def listFiles(root, patterns='*', recurse=1, return_folders=0):

    # Expand patterns from semicolon-separated string to list           
    pattern_list = patterns.split(';')
    # Collect input and output arguments into one bunch
    class Bunch:
        def _ _init_ _(self, **kwds): self._ _dict_ _.update(kwds)
    arg = Bunch(recurse=recurse, pattern_list=pattern_list,
        return_folders=return_folders, results=[])

    def visit(arg, dirname, files):
        # Append to arg.results all relevant files (and perhaps folders)
        for name in files:
            fullname = os.path.normpath(os.path.join(dirname, name))                #目录规范化
            if arg.return_folders or os.path.isfile(fullname):                      #判断是否返回目录。 是否是文件
                for pattern in arg.pattern_list:                                    #模式匹配用 "or" ,符合一个就ok
                    if fnmatch.fnmatch(name, pattern):
                        arg.results.append(fullname)                                #结果中添加文件名称
                        break
        # Block recursion if recursion was disallowed
        if not arg.recurse: files[:]=[]                               #把list中目录包含的文件/子目录置空,子目录没了哈

    os.path.walk(root, visit, arg)

    return arg.results


9.给定搜索路径(分隔符分开的欲搜索路径组成的字符串),查找第一个名称符合的文件
如:
import os, string
def search_file(filename, search_path, pathsep=os.pathsep):
    """ Given a search path, find file with requested name """
    for path in string.split(search_path, pathsep):
        candidate = os.path.join(path, filename)
        if os.path.exists(candidate): return os.path.abspath(candidate)
    return None

if _ _name_ _ == '_ _ _main_ _':
    search_path = '/bin' + os.pathsep + '/usr/bin'  # ; on Windows, : on Unix
    find_file = search_file('ls',search_path)
    if find_file:
        print "File found at %s" % find_file
    else:
        print "File not found"

10.在更新文件前,需要进行备份 : 按照标准协议是在原文件末尾加3位数字作为版本号来备份原文件
如:
def VersionFile(file_spec, vtype='copy'):
    import os, shutil

    if os.path.isfile(file_spec):
        # or, do other error checking:
        if vtype not in 'copy', 'rename':
             vtype = 'copy'

        # Determine root filename so the extension doesn't get longer
        n, e = os.path.splitext(file_spec)

        # Is e an integer?
        try:
             num = int(e)
             root = n
        except ValueError:
             root = file_spec

        # Find next available file version
        for i in xrange(1000):
             new_file = '%s.%03d' % (root, i)
             if not os.path.isfile(new_file):
                  if vtype == 'copy':
                      shutil.copy(file_spec, new_file)
                  else:
                      os.rename(file_spec, new_file)
                  return 1

    return 0

if _ _name_ _ == '_ _main_ _':
      # test code (you will need a file named test.txt)
      print VersionFile('test.txt')
      print VersionFile('test.txt')
      print VersionFile('test.txt')

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-372625-1-1.html 上篇帖子: python获取本地时间/日期格式化 下篇帖子: Python实例讲解 -- 定时播放 (闹钟+音乐)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表