Tag:python function
#--Coding:utf-8--# from sys module import argv function from sys import argv# use argv function to unpack things in argv, assign all parameters to the left variable name script sequentially, input_file = arg v# Customize a function to read the contents of F def print_all (f): Print F.read () # Custom function, use the Seek method in file to move a document cursor, to read the function of a file line in turn Def Rewind (f): F.seek (0) # The main function of the script to print the contents of each line of the file Def print_a_line (Line_Count, f): print "No.", Line_Count, F.readline () # Use the Open method in file to open Current_file = open (input_file) print "First let's print the whole file:\n" # Use a custom function Print_ All to read Open file Contents Print_all (current_file) print "Now let's rewind, kind of like a tape." # Use the above custom function Rewindrewind (current_file) print "Let's print Three lines:" # define a variable, add 1 for each line printed, and take this variable as the parameter of the Print_a_line function, Call the Print_a_line function to print each line sequentially. # The following lines of code can be written in loops to reduce the length of the code. Current_line = 1print "Now current line is:%d"% current_lineprint_a_line (Current_line, current_file) Current_line = Curr Ent_line + 1print "Now current line is:%d"% current_lineprint_a_line (Current_line, current_file) Current_line = Current_ Line + 1print "Today's line is:%d"% current_lineprint_a_line (Current_line, Current_file)
Use Python's help to query the contents of the Seek method
python -m pydoc file
Seek (...)
Seek (offset[, whence]), None. Move to new file position.
Argument offset is a byte count. Optional argument whence defaults to 0 (offset from start of file, offset should be >= 0); Other values is 1 (move relative to position, positive or negative), and 2 (moverelative to end of file, usually n Egative, although many platforms allowseeking beyond the end of a file). If the file is opened in text mode, only offsets returned by tell () is legal. Use of other offsets causes undefined behavior. Note that not all file objects is seekable.
Use + = To change the value of the variable.
a = 1print aa += 1print aa += 2print a
The results are as follows:
PS C:\python> python No20plus.py124
Python learning 20: Using functions to print the contents of a file