現在再學習幾種文件操作,順便復習一下前兩節的內容。
以下代碼實現兩個文本文件的拷貝操作。
實現流程:
1.根據參數獲取拷貝操作雙方的文件名
2.打開需要拷貝的文件
3.讀取拷貝文件內容
4.計算拷貝內容長度
5.判斷接收拷貝內容的文件路徑是否存在
6.待用戶確認是否繼續拷貝操作
7.寫模式打開接收拷貝的文件
8.寫入拷貝內容到文件
9.關閉拷貝文件
10.關閉接收拷貝的文件
一、代碼
#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()
print "This is %s,text as follows: %r" % (from_file,indata)
print "The input file is %d bytes long" % len(indata) #新函數,計算字符長度
print "Does the output file exist? %r " % exists(to_file) #新函數,判斷文件是否存在
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()
output = open(to_file, 'w')
output.write(indata)
print "Alright, all done. %s as follows:" % to_file
output = open(to_file)
print output.read()
output.close()
input.close()
這里有兩個前面沒有提到的函數:
1.len:計算對象的長度。返回整數。
E:\python\examples>python -m pydoc len
Help on built-in function len in module __builtin__:
len(...)
len(object) -> integer
Return the number of items of a sequence or collection.
2.exists:判斷文件路徑是否存在,存在返回True,不存在返回False。
E:\python\examples>python -m pydoc os.path
Help on module ntpath in os:
NAME
ntpath - Common pathname manipulations, WindowsNT/95 version.
FILE
c:\python27\lib\ntpath.py
DESCRIPTION
Instead of importing this module directly, import os and refer to this
module as os.path.
FUNCTIONS
exists(path)
Test whether a path exists.? Returns False for broken symbolic links
另外要注意的是,打開的文件寫入內容后最后需要關閉,關閉操作相當于保存。
這里的文件操作都沒提到異常捕捉,其實文件在不存在時可能會引發一個IOError,異常機制將在以后的章節中學習。