zoukankan      html  css  js  c++  java
  • python第九章文件练习1

    #encoding=utf-8
    import os
    9–1. 文件过滤. 显示一个文件的所有行, 忽略以井号( # )开头的行. 这个字符被用做
    Python , Perl, Tcl, 等大多脚本文件的注释符号.
    filename = raw_input('enter file name:')

    '''---------读取文件每一行--------'''
    fp = open(filename,'r')
    for eachLine in fp:
        print eachLine,
    '''----------追加写入文件------------'''
    fp = open(filename,'a')    #追加
    while True:
        aLine = raw_input("enter a new Line('.' to quit):")
        if aLine == '.':
            break
        else:
            fp.write('%s%s' % (aLine,os.linesep))
    '''-------统计文件所有行--------'''
    fp = open(filename,'r')
    i = 0
    for eachLine in fp:
         if(eachLine[0] != '#'):
             i += 1
             print eachLine,
    print i
    fp.close()

    # 9–2. 文件访问. 提示输入数字 N 和文件 F, 然后显示文件 F 的前 N 行.
    #ctrl+L 选中一行 按住ctrl选中多行
    #ctrl+enter 在下一行开启新行

    F = raw_input('enter file name F:')
    N = raw_input('display N Line:')
    N = int(N)
    fp = open(F,'r')
    i = 0
    for eachLine in fp:
        if i < N:
            print eachLine,
            i += 1
        else:
            break
    fp.close()

    # 9–3. 文件信息. 提示输入一个文件名, 然后显示这个文本文件的总行数.

    F = raw_input('enter file name:')
    fp = open(F,'r')
    i = 0
    for eachLine in fp:
        i += 1
    print i

    # 9–4. 文件访问. 写一个逐页显示文本文件的程序. 提示输入一个文件名, 每次显示文本
    # 文件的 25 行, 暂停并向用户提示"按任意键继续.", 按键后继续执行.

    F = raw_input('enter file name:')
    fp = open(F,'r')
    allLine = fp.readlines() 
    '''------文件总行数--------'''
    n = len(allLine)
    print n
    
    i = 1
    while 25*i < n:
        for j in range(25*(i-1),25*i):
            print j,allLine[j]
        raw_input('按任意键继续')
        i += 1
    for j in range(25*(i-1),n):
        print j,allLine[j]
    fp.close()

    # 9–6. 文件比较. 写一个比较两个文本文件的程序. 如果不同, 给出第一个不同处的行号和
    # 列号.

    def newfile():
        filename = raw_input('enter file name:')
        fp = open(filename,'a')    #追加
        while True:
            aLine = raw_input("enter a new Line('.' to quit):")
            if aLine == '.':
                break
            else:
                fp.write('%s%s' % (aLine,os.linesep))
        fp.close()
        return filename
    def displayfile(filename):
        fp = open(filename,'r')
        for eachLine in fp:
            print eachLine,
        fp.close()
    def cmpStr(str1,str2):
        #较小的字符串长度N2
        N1 = len(str1)
        N2 = len(str2)
        if N1 < N2:
            N1,N2 = N2,N1
        for i in range(N2):
            if str1[i] != str2[i]:
                return i+1
                break
            else:
                #print str1[i]
                if i == N2-1:
                    return N2 + 1
    print cmpStr('wyt','wzy')
    print cmpStr('is','is a')
    print cmpStr(['1','2'],['1','2','3'])
    
    f1 = newfile()
    displayfile(f1)
    f2 = newfile()
    displayfile(f2)
    
    fp1 = open(f1,'r')
    fp2 = open(f2,'r')
    
    aLine1 = fp1.readlines()
    aLine2 = fp2.readlines()
    
    print 'different hang is '
    print cmpStr(aLine1,aLine2)
    print aLine1[i],aLine2[i]
    i = cmpStr(aLine1,aLine2) - 1
    print 'different lie is '
    print cmpStr(aLine1[i],aLine2[i])
    fp1.close()
    fp2.close()

    #encoding=utf-8
    # 9–7. 解析文件. Win32 用户: 创建一个用来解析 Windows .ini 文件的程序. POSIX 用户:
    # 创建一个解析 /etc/serves 文件的程序. 其它平台用户: 写一个解析特定结构的系统配置文件的
    # 程序.
    #使用模块configParser不区分大小写,顺序乱。使用configobj最好
    import ConfigParser

    conf = ConfigParser.ConfigParser()
    #生成config对象
    conf.read('test.ini') #用config对象读取配置文件
    sections = conf.sections() #以列表形式返回所有的section
    print 'sections:',sections


    for i in range(len(sections)):
    print sections[i]
    #得到指定section的所有option
    options = conf.options(sections[i])
    print 'options:',options
    #得到指定section的所有键值对
    kvs = conf.items(sections[i])
    print kvs

    #指定section,option读取值
    str_val = conf.get(sections[0],'a_key1')
    print 'vaule of a_key1 is ',str_val

    '''---------------写配置文件--------------'''
    #更新指定的section,option的值
    conf.set('sec_b','b_key3','new_$r')
    #指定section,增加新的option和值
    conf.set('sec_b','b_newKey','new_value')
    #增加新的section
    conf.add_section('new_section')
    conf.set('new_section','new_section_key1','new_section_value1')
    #写回配置文件
    conf.write(open('test.ini','w'))


    # 9–8. 模块研究. 提取模块的属性资料. 提示用户输入一个模块名(或者从命令行接受输入).
    # 然后使用 dir() 和其它内建函数提取模块的属性, 显示它们的名字, 类型, 值.

  • 相关阅读:
    php composer 相关及版本约束等小技巧
    Jquery 获取表单值如input,select等方法
    Apache benchmark 压力测试工具
    Linux中的随机数文件 /dev/random /dev/urandom
    redis持久化
    Python---装饰器
    高仿拉手网底部菜单实现FragmentActivity+Fragment+RadioGroup
    python实现二叉树和它的七种遍历
    Spring AOP应用实例demo
    二维数组的列排序
  • 原文地址:https://www.cnblogs.com/lovely7/p/5761848.html
Copyright © 2011-2022 走看看