习题13
from sys import argv
script,first,second,third=argv
print("The script is called:",script)
print("The first variable is:",first)
print("The second variable is:",second)
print("The third variable is:",third)
# 需要在控制台运行并输入参数
习题14
from sys import argv
script,user_name=argv
prompt='>'
print(script) #打印该文件的路径,该参数默认存在
print("Hi {0}, I'm the {1} script".format(script,user_name))
# print(argv)
print("I'd like to ask you a few questions.")
print("Do you like me {}?".format(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.
48
21 """%(likes, lives, computer))
习题15
from sys import argv
script,filename=argv
txt=open(filename)
print("Here is your file {}".format(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 {}.".format(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
from os.path import exists
script, from_file, to_file = argv
print("Copying from {0} to {1}".format(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 {} bytes long".format(len(indata)))
print("Does the output file exist? {}".format(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()