zoukankan      html  css  js  c++  java
  • Python---进阶---文件操作---按需求打印文件的内容

    一、

    编写一个程序,当用户输入文件名和行数的时候,将该文件的前N行内容打印到屏幕上

    input 去接收一个文件名

    input 去接收一个行数

    ----------------------------------------------

    file_name = input(r"请输入你要打开的文件名: ") #是一个str
    line_name = input(r"请输入你要显示的前几行: ")
    def file_view(file_name, line_name):
        print(" 文件的%s的前%s行的内容如下" %(file_name, line_name))
       
        #去打开file_name的文件
        f = open(file_name)
        for i in range(int(line_num)):
            print(f.readline())
           
        f.close()
     
    二、
    ---------------------------------------
    我们在上一道题的基础上,增加一点功能,使用户可以随意的输入需要显示的行数
    file_name = input(r"请输入你要打开的文件名:")
    line_num = input(r"请输入你要显示的行数,格式为[1:9]或者[:]")
    def print_line(file_name, line_num):
        f = open(file_name)
       
        begin, end = line_num.split(":")
       
        if begin == "":
            begin = "1"
       
        if end == "":
            end = "-1"
           
        begin = int(begin) - 1
        end = int(end)
       
        lines = end - begin
       
        # 消耗掉begin之前的行数
        for i in range(begin):
            f.readline()
           
        if lines < 0:
            print (f.read())         
        else:
            for j in range(lines):
                print(f.readline())
       
        f.close()
       
    print_line(file_name, line_num)
    --------------------------------------------------
    三、编写一个程序,实现“全部替换”的功能
    -----------------------------------------
    -  打开一个文件
    -  把文件中xxx这样的字符串,替换成  sss
    -  open 打开文件
    -  readline 读取文件内容
    -  replace 替换
    --------------------------------------------
    file_name = input("请输入你要打开的文件名: ")
    rep_word = input("请输入你要替换的字符: ")
    new_word = input("请输入替换的字符串: ")
    def file_replace(file_name, rep_word, new_word):
       
        f = open(file_name)
        content = []
        for eachline in f:
            if rep_word in eachline:
                eachline = eachline.replace(rep_word, new_word)
               
            content.append(eachline)
           
        decide = input("你确定要这样子做吗?请输入 YES/NO")      
       
       
        if decide in ["YES", "Yes", "yes"]:
            f_write = open(file_name, "w")
            f_write.write("".join(content))
            f_write.close()
           
    file_replace(file_name, rep_word, new_word)
    --------------------------------------------------------------
    四、
  • 相关阅读:
    python应用之文件属性浏览
    python进阶之路之文件处理
    magento安装时的数据库访问错误
    magento麦进斗客户地址属性不保存在sales_flat_order_address
    自动填写麦进斗Magento进货地址字段
    麦进斗magentoRequireJs回调失败
    如何在麦进斗magento2中调用站外的JS?
    在magento1.9结账地址中删除验证
    麦进斗:在windows系统里面刷新magento2的缓存
    如何安装麦进斗Magento2
  • 原文地址:https://www.cnblogs.com/niaocaizhou/p/11059496.html
Copyright © 2011-2022 走看看