您的位置:首页 > 编程语言 > Python开发

python 手记2 〖笨方法学python习题17〗

2017-10-03 14:57 393 查看
如有意见或其他问题可在下方写下评论或拨打电话:15771314980
代码如下:
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 the line too. now?
in_file = open(from_file)
indata = in_file.read()

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

out_file = open(to_file, 'w')
out_file.write(indata)

print "Alright, all done."

out_file.close()
in_file.close()
重点内容这是习题17比较重要的几个函数与命令,如下:exists命令,这个命令将文件字符串作为参数,如果文件存在的话,它将返回True;否则将返回False。len() 函数,它会以数的形式返回你传递的字符串的长度。启迪:它会在运行结果上显示你要打印的字符串有多少个字节。自己试试吧cat命令,这个能直接在PowerShell上输入“cat <文件名>”然后它便会在PowerShell上显示那个文件的内容。强调内容.read() 一旦运行文件便会被Python关闭,所以有了.read()命令就不用.close()命令了,不过随便你把。附加练习我会将习题概括性的来一遍,那些需要查资料的习题我不写了。试着将这个脚本改短一点。练习代码如下:from sys import argv # import语句script, from_file, to_file = argv # 解包to_file = open(to_file, ‘w’) # 将文件里的内容赋给了变量“to_file”,并且用’w’特殊字符串,来进入写入模式to_file.write( open(from_file).read()) # 变量to_file现在已经带着上一个文件的内容了,所以再次用open()命令打开文件并且将变量to_file的内容复制进另一个文件找出为什么你需要在代码中写output.close()。因为:文件需要关闭,否则会出错。
-
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: