《笨辦法學Python》筆記15-----更多文件操作

現(xiàn)在再學習幾種文件操作,順便復習一下前兩節(jié)的內容。

以下代碼實現(xiàn)兩個文本文件的拷貝操作。

實現(xiàn)流程:

1.根據(jù)參數(shù)獲取拷貝操作雙方的文件名

2.打開需要拷貝的文件

3.讀取拷貝文件內容

4.計算拷貝內容長度

5.判斷接收拷貝內容的文件路徑是否存在

6.待用戶確認是否繼續(xù)拷貝操作

7.寫模式打開接收拷貝的文件

8.寫入拷貝內容到文件

9.關閉拷貝文件

10.關閉接收拷貝的文件

一、代碼

#coding:utf-8

from sys import argv

from os.path import exists #引入新函數(shù)

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) #新函數(shù),計算字符長度

print "Does the output file exist? %r " % exists(to_file) #新函數(shù),判斷文件是否存在

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()

這里有兩個前面沒有提到的函數(shù):

1.len:計算對象的長度。返回整數(shù)。

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

另外要注意的是,打開的文件寫入內容后最后需要關閉,關閉操作相當于保存。

這里的文件操作都沒提到異常捕捉,其實文件在不存在時可能會引發(fā)一個IOError,異常機制將在以后的章節(jié)中學習。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容