Python學習17:使用Python拷貝文字檔

來源:互聯網
上載者:User

標籤: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拷貝文字檔

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.