<dd id="sga4y"><optgroup id="sga4y"></optgroup></dd>
<nav id="sga4y"><code id="sga4y"></code></nav>
  • <optgroup id="sga4y"></optgroup>

    習題 17: 更多文件操作?

    現在讓我們再學習幾種文件操作。我們將編寫一個 Python 腳本,將一個文件中的內容拷貝到另外一個文件中。這個腳本很短,不過它會讓你對于文件操作有更多的了解。

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    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 one line too, how?
    input = open(from_file)
    indata = input.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()
    
    output = open(to_file, 'w')
    output.write(indata)
    
    print "Alright, all done."
    
    output.close()
    input.close()
    

    你應該很快注意到了我們 import 了又一個很好用的命令 exists。這個命令將文件名字符串作為參數,如果文件存在的話,它將返回 True,否則將返回 False。在本書的下半部分,我們將使用這個函數做很多的事情,不過現在你應該學會怎樣通過 import 調用它。

    通過使用 import ,你可以在自己代碼中直接使用其他更厲害的(通常是這樣,不過也不 盡然)程序員寫的大量免費代碼,這樣你就不需要重寫一遍了。

    你應該看到的結果?

    和你前面寫的腳本一樣,運行該腳本需要兩個參數,一個是待拷貝的文件,一個是要拷貝至的文件。如果我們使用以前的 test.txt 我們將看到如下的結果:

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

    該命令對于任何文件都應該是有效的。試試操作一些別的文件看看結果。不過小心別把你的重要文件給弄壞了。

    Warning

    你看到我用 cat 這個命令了吧?它只能在 Linux 和 OSX 下面使用,使用 Windows 的就只好跟你說聲抱歉了。

    加分習題?

    1. 再多讀讀和 import 相關的材料,將 python 運行起來,試試這一條命令。試著看看自己能不能摸出點門道,當然了,即使弄不明白也沒關系。
    2. 這個腳本 實在是 有點煩人。沒必要在拷貝之前問一遍把,沒必要在屏幕上輸出那么多東西。試著刪掉腳本的一些功能,讓它使用起來更加友好。
    3. 看看你能把這個腳本改多短,我可以把它寫成一行。
    4. 我使用了一個叫 cat 的東西,這個古老的命令的用處是將兩個文件“連接(con*cat*enate)”到一起,不過實際上它最大的用途是打印文件內容到屏幕上。你可以通過 man cat 命令了解到更多信息。
    5. 使用 Windows 的同學,你們可以給自己找一個 cat 的替代品。關于 man 的東西就別想太多了,Windows 下沒這個命令。
    6. 找出為什么你需要在代碼中寫 output.close()

    Project Versions

    Table Of Contents

    Previous topic

    習題 16: 讀寫文件

    Next topic

    習題 18: 命名、變量、代碼、函數

    This Page

    97av