《笨方法学PYTHON》——eighthlesson

习题16:读写文件

  • close——关闭文件。java的习惯是用完就得关闭,要不然会引发一系列的错误,python应该也一样。
  • read——读取文件内容。你可以把结果赋给一个变量。
  • readline——读取文本文件中的一行。
  • truncate——清空文件,请小心使用该命令。
  • write(stuff)——讲stuff写入文件。
from sys import argv

# 多变量一起赋值,起的的是多线程,一起跑的;filename可以带目录,也可以不带,不带的时候就是当前目录
script, filename = argv, "./harddemo1.txt"
# %s和%r有什么区别?我个人拙见就是%r加了个单引号...
print("We're going to erase %r." % filename)
print("If you don't want that,hit CTRL-C(^C)")
print("If you do want that,hit RETURN.")
# input没有赋给任何变量,其实没有任何意义,写一下文件的主旨吧
input("?")
print("Opening the file...")
# r——读,w——写,a——追加
target = open(filename, 'w')
# 转义,我记住的就这几个,\t——tab,\b——空格,\n——换行
print("Truncating the file.\tGoodbye!")
# 清除文件内容,和数据库的delete不加where是一样的,谨慎使用
target.truncate()
print("Now I'm going to ask you for three lines.")
# 这个input才有意义嘛
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
print("I'm going to write these to the file.")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("And finally,we close it.")
# 关闭文件对象,很有必要
target.close()

第一次加了注释,关键是觉得,这个里面的知识点还是挺多的,有这个必要,所以加了。之后都会加一下,我把输出的结果也放下面,大家参考一下。

We're going to erase './harddemo1.txt'.
If you don't want that,hit CTRL-C(^C)
If you do want that,hit RETURN.
?I love you.
Opening the file...
Truncating the file.	Goodbye!
Now I'm going to ask you for three lines.
line 1: I
line 2: love
line 3: you
I'm going to write these to the file.
And finally,we close it.

1. 如果你觉得自己没有弄懂的话,用我们的老办法,在每一行之前加上注解,为自己理清思路。就 算不能理清思路,你也可以知道自己究竟具体哪里没弄明白。

2. 写一个和上一个练习类似的脚本,使用 read 和 argv 读取你刚才新建的文件。

filename =  "harddemo1.txt"
target = open(filename, "r")
print(target.read())
target.close()

这个题目还是有必要做一下的。

也是在做这一题的时候发现的,script见名知义,是脚本的目录的意思,这个是写脚本的时候写的,我写的是直接执行的,所以这个变量可以不用。

3. 文件中重复的地方太多了。试着用一个 target.write() 将 line1, line2, line3 打 印出来,你可以使用字符串、格式化字符、以及转义字符。

4. 找出为什么我们需要给 open 多赋予一个 'w' 参数。提示: open 对于文件的写入操作态度 是安全第一,所以你只有特别指定以后,它才会进行写入操作。

target.write(line1+"\n"+line2+"\n"+line3+"\n")

5. 如果你用 'w' 模式打开文件,那么你是不是还要 target.truncate() 呢?阅读以下 Python 的 open 函数的文档找找答案

我有点迷糊了,给的脚本不是用'w'模式打开的嘛,肯定有必要呀,文件中有内容,肯定需要清除呀

 

 

习题17:更多文件操作

from os.path import exists

# 老生常谈,多线程
fromFile, toFile = 'harddemo1.txt', 'harddemo3.txt'
print("Copying from %s to %s" % (fromFile, toFile))
# we could do these two on one line too.how?
inFile = open(fromFile)
indata = inFile.read()
print("The input file is %d bytes long" % len(indata))
# 心路历程:一开始还新建了一个toFile文件,感觉没有文件时需要通过专门的指令新建,意外发现exists方法判断是false时,同样执行成功了,意思就是open时就会新建文件
print("Does the output file exist?%r" % exists(toFile))
print("Ready,hit RETURN to continue,CTRL-C to abort.")
input()
outFile = open(toFile, 'w')
outFile.write(indata)
print("Alright,all done.")
outFile.close()
inFile.close()
Copying from harddemo1.txt to harddemo3.txt
The input file is 21 bytes long
Does the output file exist?False
Ready,hit RETURN to continue,CTRL-C to abort.
登峰登山
Alright,all done.

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

os是文件操作的包

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

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

看完这个问题,有种惊呆的赶脚......

open('harddemo3.txt', 'w').write(open('harddemo1.txt').read())

原来我自己也能写出来呀,哈哈哈

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

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

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

用完就得关闭呗,哈哈哈

直接用语句with...as...就可以不用再添加close()方法:

with open(path,'w') as f:
  f.write(content)
with open(path,'r') as f:
  f.readlines()

 

 

 

 

print_r('点个赞吧');
var_dump('点个赞吧');
NSLog(@"点个赞吧!")
System.out.println("点个赞吧!");
console.log("点个赞吧!");
print("点个赞吧!");
printf("点个赞吧!\n");
cout << "点个赞吧!" << endl;
Console.WriteLine("点个赞吧!");
fmt.Println("点个赞吧!")
Response.Write("点个赞吧");
alert(’点个赞吧’)

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值