Exercise: reading files
Exercise:Read and write files
What does ' W ' mean?
It is just a special string that represents the access pattern for the file. If you use ' W ' then your file is written (write) mode. In addition to ' W ', we also have ' r ' for reading (read), ' A ' for append (append).
The most important is the + modifier, the wording is ' w+ ', ' r+ ', ' A + '-so that the file will be read and written in a way to play
And the use of file locations is somewhat different.
If you write only open (filename), do you want to use the ' R ' mode?
Yes, this is the default mode of operation of the Open () function (cannot be modified).
Exercise: more file operations
From sys import ARGV
From Os.path Import exists
Script,from_file,to_file = argv
Print "Copying from%s to%s"% (From_file,to_file)
In_file = open (From_file)
Indata = In_file.read ()
Print "The input file is%d bytes long"% len (indata)
Print "Does the output file exists? %r "% exists (To_file)
Print "Ready, hits RETURN to Continue,ctrl-c to abort."
Raw_input ()
Out_file = open (To_file, ' W ')
Out_file.write (Indata)
Print "Alright, all done."
Out_file.close ()
In_file.close ()
#另一种写法 (only one line):
From sys import ARGV
Script,from_file,to_file = argv
Open (To_file, ' W '). Write (open (from_file). Read ())
Exercise: naming, variables, code, functions
What are the rules for function names?
As with the variable name, it can be as long as it consists of alphanumeric and underscore, and not the number beginning.
What does it mean to be *args *?
Its function is to tell Python to accept all the parameters of the function and put it in the list named args.
Similar to the argv you've been using, but the former is used on the function. There is no special case, we generally do not go through
Used to this thing.
Exercise: Functions and variables
def print_two (*args):
Arg1,arg2 = args
Print "Arg1:%r, arg2:%r"% (arg1, arg2)
def print_two_again (Arg1, arg2):
Print "Arg1:%r, arg2:%r"% (arg1, arg2)
Stupid way to learn Python (2)