天天看點

python之檔案的複制

<code>import</code> <code>os</code>

<code>old_file_name </code><code>=</code> <code>input</code><code>(</code><code>"Please input what's file do you want to copy go:"</code><code>)</code>

<code>fp </code><code>=</code> <code>open</code><code>(old_file_name)</code>

<code>content </code><code>=</code> <code>fp.read()</code>

<code>index </code><code>=</code> <code>old_file_name.rfind(</code><code>'.'</code><code>)</code>

<code>new_file_name </code><code>=</code> <code>old_file_name[:index]</code><code>+</code><code>"[複件]"</code><code>+</code><code>old_file_name[index:]</code>

<code>dp </code><code>=</code> <code>open</code><code>(new_file_name,</code><code>'w'</code><code>)</code>

<code>dp.write(content)</code>

上面代碼是檔案的複制,我們的思路是這樣的:

你可以打開一個存在的檔案,然後去讀取這個檔案的内容,然後去建立一個新的檔案,這個檔案的名字是舊檔案名字後面加上[複件]這樣的字型。然後把我們剛剛在舊檔案中讀到的内容寫到新檔案裡面去。關閉兩個檔案就好啦。

第二行讓使用者輸入你想複制的檔案,這個檔案必須存在,而且最好是絕對路徑。

第四行是打開我們要舊檔案,用content變量是儲存舊檔案裡面的内容

第五行去查找old_file_name這個變量的字元串中最右邊出現的一個'.'符号的下标。

第六行是給new檔案命名,然後賦予給變量new_file_name這個變量啊

那麼上面有一個問題,如果說我們要複制一個你不知多大的檔案的時候,千萬不要用read,因為read會把所有的内容都讀進記憶體,如果這個檔案很大你的記憶體就崩了,也不要用readlines因為如果你的檔案内容隻有一行,這一行的資料很大,那你的記憶體也會被影響到。

可以用下面代碼:

<code>while</code> <code>True</code><code>:</code>

<code>    </code><code>content </code><code>=</code> <code>fp.read(</code><code>1024</code><code>)</code>

<code>    </code><code>if</code> <code>len</code><code>(content) </code><code>=</code><code>=</code> <code>0</code><code>:</code>

<code>        </code><code>break</code>

<code>    </code><code>dp.write(content)</code>

<code>fp.close()</code>

<code>dp.close()</code>

上面代碼的第8行是讀這個檔案的前1024個字元,然後再去判斷讀出來的内容是不是為空的,如果是的話就break退出循環,如果不是就就把内容寫入新檔案中

本文轉自 周子琪 51CTO部落格,原文連結:http://blog.51cto.com/izhouyu/1967644