习题 13: 参数、解包、变量
from sys import argv
script,first,second,third = argv
print("The script is called:",script)
print("Your first variable is:",first)
print("Your second variable is:",second)
print("Your third variable is:",third)
#在Run/Debug Configurations 里Script parameters设置argy 参数
习题 14: 提示和传递
from sys import argv
script,user_name = argv
prompt ="> "
print("Hi %s, I'm the %s script."% (user_name,script))
print("I'd like to ask you a few questions.")
print("Do you like me %s?"% user_name)
likes =input(prompt)
print("Where do you live %s"% user_name)
lives =input(prompt)
print("What kind of computer do you have?")
computer =input(prompt)
print("""
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice.
"""% (likes,lives,computer))
习题 15:读取文件
fromsysimportargv
script,filename = argv
txt =open(filename)
print("Here's your file %r:"% filename)
print(txt.read())
print("Type the filename again:")
file_again =input("> ")
txt_again =open(file_again)
print(txt_again.read())
习题 16:读写文件
from sys import argv
script,filename = argv
print("We're going to erase %r."% filename)
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, hit RETURN.")
input("?")
print("Opening the file ...")
target =open(filename,"w")
print("Truncating the file. Goodbye!")
target.truncate()
print("Now I'm going to ask you for three lines.")
line1 =input("line 1: ")
line2 =input("line 2: ")
line3 =input("line 3: ")
print("I'm going to write these to the file.")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("And finally, we close it.")
target.close()
习题 17: 更多文件操作
from sys import argv
fromos.pathimportexists
script,from_file,to_file = argv
print("Copying from %s to %s"% (from_file,to_file))
# we could do these two on one line too, how?
get =open(from_file)
indata = get.read()
print("The input file is %d bytes long"%len(indata))
print("Does the output file exist? %r"% exists(to_file))
print("Ready, hit RETURN to continue, CTRL-C to abort.")
input()
output =open(to_file,"w")
output.write(indata)
print("Alright, all done.")
output.close()
get.close()