亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

習(xí)題 16: 讀寫文件?

如果你做了上一個(gè)練習(xí)的加分習(xí)題,你應(yīng)該已經(jīng)了解了各種文件相關(guān)的命令(方法/函數(shù))。你應(yīng)該記住的命令如下:

  • close – 關(guān)閉文件。跟你編輯器的 文件->保存.. 一個(gè)意思。
  • read – 讀取文件內(nèi)容。你可以把結(jié)果賦給一個(gè)變量。
  • readline – 讀取文本文件中的一行。
  • truncate – 清空文件,請(qǐng)小心使用該命令。
  • write(stuff) – 將stuff寫入文件。

這是你現(xiàn)在該知道的重要命令。有些命令需要接受參數(shù),這對(duì)我們并不重要。你只要記住 write 的用法就可以了。 write 需要接收一個(gè)字符串作為參數(shù),從而將該字符串寫入文件。

讓我們來使用這些命令做一個(gè)簡(jiǎn)單的文本編輯器吧:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from sys import argv

script, filename = argv

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."

raw_input("?")

print "Opening the file..."
target = open(filename, 'w')

print "Truncating the file.  Goodbye!"
target.truncate()

print "Now I'm going to ask you for three lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_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()

這個(gè)文件是夠大的,大概是你鍵入過的最大的文件。所以慢慢來,仔細(xì)檢查,讓它能運(yùn)行起來。有一個(gè)小技巧就是你可以讓你的腳本一部分一部分地運(yùn)行起來。先寫 1-8 行,讓它運(yùn)行起來,再多運(yùn)行 5 行,再接著多運(yùn)行幾行,以此類推,直到整個(gè)腳本運(yùn)行起來為止。

你應(yīng)該看到的結(jié)果?

你將看到兩樣?xùn)|西,一樣是你新腳本的輸出:

$ python ex16.py test.txt
We're going to erase 'test.txt'.
If you don't want that, hit CTRL-C (^C).
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file.  Goodbye!
Now I'm going to ask you for three lines.
line 1: To all the people out there.
line 2: I say I don't like my hair.
line 3: I need to shave it off.
I'm going to write these to the file.
And finally, we close it.
$

接下來打開你新建的文件(我的是 test.txt )檢查一下里邊的內(nèi)容,怎么樣,不錯(cuò)吧?

加分習(xí)題?

  1. 如果你覺得自己沒有弄懂的話,用我們的老辦法,在每一行之前加上注解,為自己理清思路。就算不能理清思路,你也可以知道自己究竟具體哪里沒弄明白。
  2. 寫一個(gè)和上一個(gè)練習(xí)類似的腳本,使用 readargv 讀取你剛才新建的文件。
  3. 文件中重復(fù)的地方太多了。試著用一個(gè) target.write()line1, line2, line3 打印出來,你可以使用字符串、格式化字符、以及轉(zhuǎn)義字符。
  4. 找出為什么我們需要給 open 多賦予一個(gè) 'w' 參數(shù)。提示: open 對(duì)于文件的寫入操作態(tài)度是安全第一,所以你只有特別指定以后,它才會(huì)進(jìn)行寫入操作。

Project Versions

Table Of Contents

Previous topic

習(xí)題 15: 讀取文件

Next topic

習(xí)題 17: 更多文件操作

This Page