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()。因为:文件需要关闭,否则会出错。-
相关文章推荐
- python 手记8 〖笨方法学python习题29〗
- 笨方法写python 习题17
- python 手记11 『笨方法学python 习题32』
- python 手记4 〖笨方法学python习题19〗
- python 手记10 『笨方法学python 习题31』
- python 手记5 〖笨方法学python习题20〗
- python 手记6 〖笨方法学python习题21〗
- python 手记7 〖笨方法学python习题22〗
- 笨方法学Python 习题 17: 更多文件操作
- 笨方法学习Python-习题17: 更多文件操作
- python 手记9 〖笨方法学python习题30〗
- python手记(游戏) 笨方法学python习题36【持续更新中】
- 笨方法学Python 习题 15: 读取文件
- 笨方法学Python 习题 28: 布尔表达式练习
- 笨方法学习Python-习题30: Else 和 If
- 笨方法学Python习题47—自动化测试
- 笨方法学Python 习题0
- 笨方法学习Python-习题20: 函数和文件
- 笨方法学Python—习题41:学习面向对象术语
- 笨方法学Python 习题 23: 读代码