zoukankan      html  css  js  c++  java
  • Python核心编程第二版 第九章课后答案

    9-1.文件过滤。显示一个文件的所有行,忽略以井号(#)开头的行。这个字符被用做Python,Perl,Tcl,等大多数脚本文件的注释符号。附加题:处理不是第一个字符开头的注释。

    f = open(filename, 'r')
    allLines = f.readlines()
    for line in allLines:
    #     print(line,)
        if line[0] != '#':
            print(line,)
     
    f.close()

    9-2.文件访问。提示输入数字N和文件F,然后显示文件F的前N行。

    filename = input('Enter the file name:')
    N = int(input('Enter the number of rows:'))
    f = open(filename, 'r')
    allLines = f.readlines()
    i = 1
    for line in allLines:
        print(line,)
        if i == N:
            break
        i = i + 1
     
    f.close()

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

    filename = input('Enter the file name:')
    f = open(filename, 'r')
    allLines = f.readlines()
    print(len(allLines))
     
    f.close()

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

    filename = input('Enter the file name:')
    f = open(filename, 'r')
    allLines = f.readlines()
    i = 0
    for line in allLines:
        if i != 5:
            print(line,)
        else:
            ele = input('Press any key to continue')
            i = 0
            
        i = i + 1
     
    f.close()

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

    def fileCompare(file1,file2):
        f1 = open(file1, 'r')
        f2 = open(file2, 'r')
        allLines1 = f1.readlines()
        allLines2 = f2.readlines()
        
        if len(allLines1) >= len(allLines2):
            biglen = len(allLines1)
        else:
            biglen = len(allLines2)
        for i in range(biglen):
            if allLines1[i] != allLines2[i]:
                row = i + 1
                if len(allLines1[i]) >= len(allLines2[i]):
                    biglen2 = len(allLines1[i])
                else:
                    biglen2 = len(allLines2[i])
                for col in range(biglen2):
                    if allLines1[i][col] != allLines2[i][col]:
                        print('row:%d,col:%d' %(row,col+1))
                        return None
        print('文件相同')
         
        f1.close()
        f2.close()
  • 相关阅读:
    nio非阻塞缓存流
    java高级---->Thread之ScheduledExecutorService的使用
    ScheduledExecutorService-spring-定时周期执行指定的任务
    常用数据库连接池 (DBCP、c3p0、Druid) 配置说明
    Linux定时任务Crontab命令详解
    mybatis xml查询语句大全
    mysql索引研究
    关于HttpClient重试策略的研究
    对于org.apache.commons.dbcp.BasicDataSource的配置认知
    Linux dos2unix命令
  • 原文地址:https://www.cnblogs.com/jiaoyang77/p/7487264.html
Copyright © 2011-2022 走看看