《笨办法学Python》笔记15-----更多文件操作

现在再学习几种文件操作,顺便复习一下前两节的内容。

以下代码实现两个文本文件的拷贝操作。

实现流程:

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,异常机制将在以后的章节中学习。

你可能感兴趣的:(《笨办法学Python》笔记15-----更多文件操作)