1. 程式人生 > >python中sys模組的argv

python中sys模組的argv

"""笨辦法學python,啟動時在命令列中python 指令碼檔名 filename"""
from sys import argv

# argv - 命令列引數; argv[0]是指令碼路徑名python,sys.argv[0]表示指令碼路徑名
script, filename = argv # 指令碼和檔名稱
print("We're going to erase %r." % filename) # 正常使用%s,在這裡%r是為了重現它代表的物件
print("If you don't want that, hit RETURN-C (^C).")
print("If you do want that, hit RETURN.")
input("?") # 單純的?號
print("Opening the file...")
target = open(filename, "w") # 以"w"寫入的形式開啟檔案,a表示追加,r表示讀取。不寫預設是讀取操作
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() # 關閉已開啟的檔案