Python學習17:使用Python拷貝文本文件
阿新 • • 發佈:2018-02-23
import ctr ould 程序 line data 模塊 代碼 raw 編寫一個Python腳本,將一個文件的內容拷貝到另一個文件
# -- coding: utf-8 -- from sys import argv from os.path import exists 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? # input = open(from_file) # indata = input.read() indata = open(from_file).read() #print "Here is indata: %r" % indata #print #print indata print "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() print print indata
使用import整個模塊的方式改寫代碼:
import sys #導入sys模塊,可以讀寫文件內容 import os #導入os模塊,可以使用exists方法查詢文件是否存在 script, from_file, to_file = sys.argv input = 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拷貝文本文件