標籤:port code 存在 from script 學習 匯入 raw lin
編寫一個Python指令碼,將一個檔案的內容拷貝到另一個檔案
# -- coding: utf-8 --from sys import argvfrom os.path import existsscript, from_file, to_file = argvprint "Copying from %s to %s " % (from_file, to_file)# we could do these two on one line too, how?# input = open(from_file)# indata = input.read()indata = open(from_file).read()#print "Here is indata: %r" % indata#print#print indataprint "The input file is %d bytes long" % len(indata)print "Does the output file exists? %r" % exists(to_file)print "Ready, hit RETURN to continue, CTRL-C to abort."raw_input("RETURN or CTRL-C > ")# 如果to_file不存在的話,程式會自動在指令碼目前的目錄建立檔案,檔案名稱為你給的第二個參數output = open(to_file, ‘w‘)output.write(indata)print "Alright, all done."output.close()printprint indata
使用import整個模組的方式改寫代碼:
import sys #匯入sys模組,可以讀寫檔案內容import os #匯入os模組,可以使用exists方法查詢檔案是否存在script, from_file, to_file = sys.argvinput = open(from_file)indata = input.read()print "Does the output file exists? %r" % os.path.exists(to_file)raw_input("continue? ‘RETURN‘ for continue, ‘CTRL-C‘ for abort. >")output = open(to_file, ‘w‘)output.write(indata)print "Alright, done."output.close()input.close()
Python學習17:使用Python拷貝文字檔