Advanced Python --- --- --- content file operations on demand print file

One,

Write a program that, when users enter the file name and line number of the first N rows contents of the file printed to the screen

input to receive a file name

input to receive a number of rows

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

file_name = input (r "Please enter the name of the file you want to open:") # is a str
LINE_NAME the INPUT = (r "Please enter the first few rows you want to display:")
DEF file_view (file_name, LINE_NAME):
    Print ( "\ SUMMARY front% s line% s of n files as"% (file_name, LINE_NAME))
   
    # to open file_name file
    F = Open (file_name)
    for I in Range ( int (line_num)):
        Print (f.readline ())
       
    f.close ()
 
two,
---------------------------------------
We are on the basis of a question, a little more functionality, so that users can input the number of rows to be displayed
file_name = input (r "Please enter your want to open the file name:")
line_num = the INPUT (r "Please enter the number of rows you want to display, format [1: 9] or [:]")
DEF print_line (file_name, line_num):
    F = Open (file_name)
   
    the begin, End = line_num.split ( ":")
   
    IF the begin == "":
        the begin = ". 1"
   
    IF End == "":
        End = "-1"
       
    the begin = int ( begin) -. 1
    End = int (End)
   
    lines = End - begin
   
    # consumed before the begin line number
    for I in Range (begin):
        f.readline ()
       
    IF lines <0:
        Print (reached, f.read ())         
    the else :
        for J in the Range (Lines):
            Print (f.readline ())
   
    f. close()
   
print_line(file_name, line_num)
--------------------------------------------------
Third, write a program to achieve "Replace All" function
-----------------------------------------
- Open a file
- the file xxx this string replaced sss
- open Open File
- readline to read the file contents
- replace replace
--------------------------------------------
file_name = input ( "Please enter the name of the file you want to open:")
rep_word the INPUT = ( "Please enter the characters you want to replace:")
new_word the INPUT = ( "Please enter the replacement string:")
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 the INPUT = ( "Are you sure you want to like this ? child do you enter YES / NO ")      
   
   
    IF Decide in [" YES "," Yes "," yes "]:
        f_write = Open (file_name," w ")
        f_write.write (" "the Join (Content.))
        f_write.close ()
       
file_replace (file_name, rep_word, new_word)
--------------------------------------------------------------
four,

Guess you like

Origin www.cnblogs.com/niaocaizhou/p/11059496.html