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

笨方法学Python 习题 17: 更多文件操作

2017-07-27 17:09 429 查看
#!usr/bin/python
# -*-coding:utf-8-*-

from sys import argv
from os.path import exists

script , from_file , to_file = argv
# 定义值 script=lx0017.py from_file=test.txt to_file=copied.txt

print ("Copting from %s to %s" % (from_file , to_file))
# 打印 Copying from test.txt to copied.txt

in_file = open(from_file)
# 打开from_file定义in+file
indata = in_file.read()
# 读取in_file定义indata

print ("The input file is %d bytes long" % len(indata))
# 打印indata字符数

print ("Does the output file exist? %r" % exists(to_file))
# exists判断文件和文件夹是否存在

print ("Ready, hit RETURN to continue, CTRL-C to abort.")
# 打印 Ready, hit RETURN to continue, CTRL-C to abort.

input()

out_file = open(to_file , "w")
# 以写模式 打开copied.txt
# w代表写模式打开文件
# r代表读模式打开文件
# wr代表读写模式打开文件
# w+代表读写模式打开文件
# r+代表读写模式打开文件
# a+代表读写模式打开文件
out_file.write(indata)
# 打开out_file写入indata

print ("Alriht , all done.")
# 打印

out_file.close()
# 关闭out_file
in_file.close()
# 关闭in_file



运行结果如下:
$ python ex17.py test.txt copied.txt
Copying from test.txt to copied.txt
The input file is 81 bytes long
Does the output file exist? False
Ready, hit RETURN to continue, CTRL-C to abort.

Alright, all done.

$ cat copied.txt
To all the people out there.
I say I don't like my hair.
I need to shave it off.
$
加分习题

再多读读和 import 相关的材料,将 python 运行起来,试试这一条命令。试着看看自己能不能摸出点门道,当然了,即使弄不明白也没关系。

这个脚本 实在是 有点烦人。没必要在拷贝之前问一遍把,没必要在屏幕上输出那么多东西。试着删掉脚本的一些功能,让它使用起来更加友好。

from sys import argv
from os.path import exists

script , from_file , to_file = argv
in_file = open(from_file)
indata = in_file.read()
out_file = open(to_file , "w")
out_file.write(indata)
out_file.close()
in_file.close()

看看你能把这个脚本改多短,我可以把它写成一行。

open(to_file,"w").write(open(from_file).read())
我使用了一个叫 cat 的东西,这个古老的命令的用处是将两个文件“连接(con*cat*enate)”到一起,不过实际上它最大的用途是打印文件内容到屏幕上。你可以通过 man cat 命令了解到更多信息。

使用 Windows 的同学,你们可以给自己找一个 cat 的替代品。关于 man 的东西就别想太多了,Windows 下没这个命令。

找出为什么你需要在代码中写 output.close() 。

常见问题回答

为什么 'w' 要放在括号中?

因为这是一个字符串,你已经学过一阵子字符串了,确定自己真的学会了。

不可能把这写在一行里边!

取决于你的行是怎么定义的——例如这样: That ; depends ; on ; how ; you ; define ; one ; line ; of ; code.

len() 函数的功能是什么?

它会以数字的形式返回你传递的字符串的长度。试着玩玩吧。

当我把代码写短时,我在关闭文件时出现一个错误。

很可能是你写了 indata = open(from_file).read() 这意味着你无需再运行``in_file.close()`` 了,因为 read() 一旦运行, 文件就会被读到结尾并且被 close 掉。

我觉得这个习题很难,这个是正常现象吗?

是的,再正常不过了。也许在你看到习题 36 之前,甚至读完本书,编程对你来说都还是一件很难理解的事情。每个人的情况都不一样,坚持读书做练习,有问题的地方多研究,总会弄明白的。慢工出细活。

Syntax:EOL while scanning string literal 错误。

字符串结尾忘记加引号了。仔细检查那行看看。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息