文件處理對於任何程式設計師來說都是至關重要的技能。每個開發者都應該能夠存取外部來源的資料並與之交互,並實現計算和儲存。
檔案用於在磁碟上儲存資料。它們可以包含文字、數字或二進位資料。在 Python 中,我們使用內建函數和方法來處理檔案。
要開啟文件,我們使用 open() 函數。它有兩個主要參數:
常用模式
範例:
file = open("scofield.txt", "w")
在這個例子中,我們創建了一個名為 file 的變量,我們說它應該調用 scofield.txt,其中我們附加“w”來覆蓋其中寫入的任何內容。
寫入檔案
要寫入文件,請使用 write() 方法。
file = open("scofield.txt", "w") file.write("Hello, World!") file.close()
完成後關閉文件以釋放系統資源非常重要。更好的做法是使用 with 語句,它會自動關閉檔案。
with open("scofiedl.txt", "w") as file: file.write("Hello, World!")
覆蓋裡面的內容後,我們寫了上面的程式碼,但使其更短,使用 with open 指令關閉 scofield.txt。
從檔案讀取
您可以使用多種方法來讀取文件。
read(): Reads the entire file readline(): Reads a single line readlines(): Reads all lines into a list
範例:
with open("scofield.txt", "r") as file: content = file.read() print(content)
附加到檔案
若要將內容新增至現有文件而不覆蓋,請使用追加模式:
with open("scofield.txt", "a") as file: file.write("\nThis is a new line.")
您可以新增至現有文件,而不是總是覆蓋現有文件,如果您有一個正在進行的專案並希望存取先前的工作,這是一個很好的方法。
為了充分理解文件處理的下一個方面,我們必須暫停學習並深入研究模組和函式庫。
Python 如此通用和強大的關鍵功能之一是其廣泛的模組和庫生態系統。這些工具可讓您擴展 Python 的功能,使複雜的任務變得更簡單,並使您能夠編寫更有效率、更強大的程式。
什麼是模組和函式庫?
從本質上講,Python 中的模組只是一個包含 Python 程式碼的檔案。它可以定義程式中可使用的函數、類別和變數。另一方面,庫是模組的集合。將模組視為單獨的工具,而函式庫是包含多個相關工具的工具箱。
模組和函式庫的主要目的是促進程式碼可重用性。您可以使用預先編寫的、經過測試的程式碼來執行常見任務,而不是從頭開始編寫所有內容。這可以節省時間並減少程式出錯的機會。
內建模組
Python 附帶了一組內建模組,它們是標準函式庫的一部分。這些模組在每個 Python 安裝中都可用,提供廣泛的開箱即用功能。讓我們探討幾個例子。
「隨機」模組用來產生隨機數。使用方法如下:
import random # Generate a random integer between 1 and 10 random_number = random.randint(1, 10) print(random_number) # Choose a random item from a list fruits = ["apple", "banana", "cherry"] random_fruit = random.choice(fruits) print(random_fruit)
在這個範例中,我們先導入 random 模組。然後我們使用它的 randint 函數產生一個隨機整數,並使用它的 'choice' 函數從列表中選擇一個隨機項目。
「datetime」模組提供了處理日期和時間的類別:
import datetime # Get the current date and time current_time = datetime.datetime.now() print(current_time) # Create a specific date birthday = datetime.date(1990, 5, 15) print(birthday)
在這裡,我們使用 datetime 模組來取得當前日期和時間,並建立一個特定的日期。
「數學」模組提供數學函數。
import math # Calculate the square root of a number sqrt_of_16 = math.sqrt(16) print(sqrt_of_16) # Calculate the sine of an angle (in radians) sine_of_pi_over_2 = math.sin(math.pi / 2) print(sine_of_pi_over_2)
此範例示範如何使用「數學」模組來執行數學計算。
導入模組
Python 中有多種導入模組的方法:
導入整個模組
import random random_number = random.randint(1, 10)
Import specific functions from a module
from random import randint random_number = randint(1, 10)
Import all functions from a module (use cautiously)
from random import * random_number = randint(1, 10)
Import a module with an alias
While the standard library is extensive, Python's true power lies in its vast ecosystem of third-party libraries. These libraries cover various functionalities, from web development to data analysis and machine learning.
To use external libraries, you first need to install them. This is typically done using pip, Python's package installer. Here's an example using the popular 'requests' library for making HTTP requests.
Install the library
pip install requests
Use the library in your code
import requests response = requests.get('https://api.github.com') print(response.status_code) print(response.json())
This code sends a GET request to the GitHub API and prints the response status and content.
Our response was a 200, which means success; we were able to connect to the server.
Creating Your Own Modules
You might want to organize your code into modules as your projects grow. Creating a module is as simple as saving your Python code in a .py file. For example, let's create a module called 'write.py'
The key is to ensure all your files are in a single directory so it's easy for Python to track the file based on the name.
with open("scofield.txt", "w") as file: content = file.write("Hello welcome to school")
Now, you can use this module in another Python file, so we will import it to the new file I created called read.py as long as they are in the same directory.
import write with open("scofield.txt", "r") as file: filenew = file.read() print(filenew)
Our result would output the write command we set in write.py.
When you import a module, Python looks for it in several locations, collectively known as the Python path. This includes.
Understanding the Python path can help you troubleshoot import issues and organize your projects effectively.
Best Practices
Modules and libraries are fundamental to Python programming. They allow you to leverage existing code, extend Python's functionality, and effectively organize your code.
Now you understand imports, let's see how it works with file handling.
import os file_path = os.path.join("folder", "scofield_fiel1.txt") with open(file_path, "w") as file: file.write("success comes with patience and commitment")
First, we import the os module. This module provides a way to use operating system-dependent functionality like creating and removing directories, fetching environment variables, or in our case, working with file paths. By importing 'os', we gain access to tools that work regardless of whether you're using Windows, macOS, or Linux.
Next, we use os.path.join() to create a file path. This function is incredibly useful because it creates a correct path for your operating system.
On Windows, it might produce "folder\example.txt", while on Unix-based systems, it would create "folder/scofield_file1.txt". This small detail makes your code more portable and less likely to break when run on different systems.
The variable 'file_path' now contains the correct path to a file named "example.txt" inside a folder called "folder".
As mentioned above, the with statement allows Python to close the file after we finish writing it.
open()函數用於開啟檔案。我們向它傳遞兩個參數:我們的 file_path 和模式「w」。 「w」模式代表寫入模式,如果文件不存在則建立該文件,如果存在則覆寫該文件。其他常見模式包括“r”表示讀取和“a”表示追加。
最後,我們使用 write() 方法將一些文字放入檔案中。文字「Using os.path.join for file paths」將被寫入該文件,表示我們已使用適用於任何作業系統的路徑成功建立並寫入文件。
如果你喜歡我的工作並想幫助我繼續刪除這樣的內容,請給我一杯咖啡。
如果您覺得我們的貼文令人興奮,請在 Learnhub 部落格上找到更多令人興奮的貼文;我們編寫從雲端運算到前端開發、網路安全、人工智慧和區塊鏈的所有技術。
以上是Python:從初學者到專業人士第 4 部分的詳細內容。更多資訊請關注PHP中文網其他相關文章!