Python---進階---文件操作---按需求打印文件的內容


一、

編寫一個程序,當用戶輸入文件名和行數的時候,將該文件的前N行內容打印到屏幕上

input 去接收一個文件名

input 去接收一個行數

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

file_name = input(r"請輸入你要打開的文件名: ") #是一個str
line_name = input(r"請輸入你要顯示的前幾行: ")
def file_view(file_name, line_name):
    print("\n文件的%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)
--------------------------------------------------------------
四、


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM