python学习5——提示、传递以及读写文件。

一、import命令。

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)

输出结果:

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 know more about you.")
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 likeing me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice.
''' %(likes, lives, computer))

输出结果(注意:运行时要将名字赋给脚本,此处输入Nick为名字)

 二、读写文件。

from sys import argv
script, filename = argv 
print(" We are going to change %r." % filename)
print("If you don't want that, hit Esc.")
print("If you do want that, hit Enter.")
input("?")
print("opening the file...")
target = open( filename,'w')
print("Goodbye!")
target.truncate()
print("Now I'm goinf 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("
")
target.write(line2)
target.write("
")
target.write(line3)
target.write("
")
print("And then, we change it.")

此处建立一个空的txt文件,命名为10.py

输出结果:

并且打开10.txt,文件已经被写入。 

 三、读取文件。

from sys import argv
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())

输出结果:

原文地址:https://www.cnblogs.com/shannon-V/p/9516903.html