第21題 Write To A File(寫入文件) <<
Previous Next >> 解答-3
題目-3
Exercise 21
Take the code from the How To Decode A Website exercise (if you didn’t do it or just want to play with some different code, use the code from the solution), and instead of printing the results to a screen, write the results to a txt file. In your code, just make up a name for the file you are saving to.
Extras:
- Ask the user to specify the name of the output file that will be saved.
Discussion
Topics:
- Writing to a file
- Gotchas and warnings
Saving to a file
Python makes it very easy to write to a file. Depending on what kind of file you want to write to and what kind of data you are writing, your options are plenty. I will show you the simplest form of writing to a file - writing plain text to a plain old text file. In other words, writing a string to a .txt
file.
The code looks like this:
An alternate way of writing the same code is like so:
The first is considered better programming practice, but the second might explain a little bit better what is going on in the first code sample.
Let’s go through line by line.
The with open('file_to_save.txt', 'w') as open_file
syntax is new for us - all it means is that inside the code block indented underneath, there will be a variable called open_file
that will represent the file object. You can pick any name for this file - it is just a variable name. The open()
function takes two arguments - the first is the name of a file as a string (if the file does not exist, Python will create it), and a second argument that represents how the file should be opened. There are a few ways you can open files (read all about it at the official Python documentation), but in short, there are two most common ones: 'r'
and 'w'
. 'r'
stands for “read only” and 'w'
stands for “write only” (you can open for both read and write using 'r+'
). You should tell Python which way you want to open the file - you don’t want to modify a file you are only looking at, and opening a file with 'w'
when you want to only read it will overwrite the old file.
When you open a file, it will look for it in the same directory as the Python program. If there is no file with that name, Python will create a file in that directory with the given name. To look for files in other directories, use the ../
notation to move up and down directories as necessary.
As soon as the program exists the with
code block for any reason, it will close the file. In the second code example case, I created the file object by opening the file and saving the object to my variable open_file
. I then had to remember to close the file manually at the end of my program. This is considered worse programming practice, because in case there is an error in the program and it terminates before hitting the .close()
statement, there will be a floating open file object somewhere in memory. You do this enough times and it becomes a problem, especially for production environments. For playing around with Python, this is not usually a problem, but why not learn how to program correctly the first time?
The write()
portion is simple - call .write()
with a string (if something is not a string, turn it into a string first), and it will write to the end of the file.
When the program exists the with
statement, the file will automatically be saved. In fact, every time after a .write()
statement, the file will be automatically saved.
Gotchas and Warnings
This all seems simple enough, but there are a few caveats to the file-writing endeavor.
- You always want to make sure you close a file. The easiest strategy for this is explained above - use the
with
statement rather than trying to manually remember to .close()
the file.
- Opening a file for writing with
'w'
will overwrite any file that currently exists with that name. If you have previously written data to that file, it is now gone as soon as Python opens it.
- You can write any kind of object to any kind of file in Python, as long as you specify the correct format. The simplest thing to do is to write strings to a
.txt
file. But remember - you have to convert numbers or objects into strings before you write them to a file. In a later exercise, we’ll talk about writing to other formats.
The best way to remember the caveats is to explore them yourself, so have at it!
練習21
從“如何對網站進行解碼”練習中獲取代碼(如果您沒有這樣做,或者只是想使用一些不同的代碼,請使用解決方案中的代碼),而不是將結果打印到屏幕上,而是將結果寫到屏幕上到txt文件。在您的代碼中,只需為要保存到的文件命名。
附加功能:
討論區
主題:
- 寫入文件
- 陷阱和警告
保存到文件
Python使寫入文件變得非常容易。根據要寫入的文件類型和要寫入的數據類型,您有很多選擇。我將向您展示寫入文件的最簡單形式-將純文本寫入純舊文本文件。換句話說,將字符串寫入.txt
文件。
代碼如下:
編寫相同代碼的另一種方法是這樣的:
第一種被認為是更好的編程實踐,但是第二種可能會更好地解釋第一個代碼示例中發生的事情。
讓我們逐行進行。
該with open('file_to_save.txt', 'w') as open_file
語法是新的我們-所有這意味著內的代碼塊縮進下,會有一個叫做變量open_file
將代表文件對象。您可以為此文件選擇任何名稱-它只是一個變量名。該open()
函數有兩個參數-第一個是文件作為一個字符串(如果文件不存在,Python將創建它),並表示第二個參數的名稱如何文件應該被打開。您可以通過幾種方式打開文件(有關詳細信息,請參見Python的官方文檔),總之,有兩種最常見的方式:'r'
和'w'
。'r'
代表“只讀”和'w'
“只寫”(您可以使用'r+'
)。您應該告訴Python您想以哪種方式打開文件-您不想修改僅查看的文件,'w'
而只想讀取文件時打開文件將覆蓋舊文件。
當您打開文件時,它將在與Python程序相同的目錄中查找。如果沒有使用該名稱的文件,Python將在該目錄中使用給定名稱創建一個文件。要在其他目錄中查找文件,請../
根據需要使用表示法在目錄中上下移動。
一旦程序with
由於某種原因存在代碼塊,它將關閉文件。在第二個代碼示例案例中,我通過打開文件並將對象保存到我的變量中來創建文件對象open_file
。然後,我必須記住在程序結束時手動關閉文件。這被認為是較差的編程習慣,因為如果程序中出現錯誤並且在命中該.close()
語句之前終止該錯誤,則在內存中的某個位置將有一個浮動的打開文件對象。您執行此操作的次數足夠多,這將成為一個問題,尤其是對於生產環境。對於使用Python來說,這通常不是問題,但是為什麼不第一次學習如何正確編程呢?
該write()
部分很簡單-.write()
用字符串調用(如果不是字符串,請先將其轉換為字符串),然後它將寫入文件的末尾。
當程序存在該with
語句時,文件將自動保存。實際上,每次.write()
聲明後,文件都會自動保存。
陷阱和警告
這一切似乎很簡單,但是文件編寫工作有一些警告。
- 您始終要確保關閉文件。上面已說明了最簡單的策略-使用該
with
語句,而不是嘗試手動記住.close()
該文件。
- 打開要寫入的文件
'w'
將覆蓋該名稱當前存在的任何文件。如果您之前已將數據寫入該文件,則Python打開後立即消失。
- 只要指定正確的格式,就可以在Python中將任何類型的對象寫入任何類型的文件。最簡單的方法是將字符串寫入
.txt
文件。但是請記住-在將數字或對象寫入文件之前,必須將其轉換為字符串。在以後的練習中,我們將討論編寫其他格式的內容。
第21題 Write To A File(寫入文件) <<
Previous Next >> 解答-3