首頁 > 後端開發 > Python教學 > Python:從初學者到專業人士第 4 部分

Python:從初學者到專業人士第 4 部分

王林
發布: 2024-07-24 13:59:51
原創
413 人瀏覽過

文件處理:學習讀取和寫入文件

文件處理對於任何程式設計師來說都是至關重要的技能。每個開發者都應該能夠存取外部來源的資料並與之交互,並實現計算和儲存。

檔案用於在磁碟上儲存資料。它們可以包含文字、數字或二進位資料。在 Python 中,我們使用內建函數和方法來處理檔案。

要開啟文件,我們使用 open() 函數。它有兩個主要參數:

  • 檔案路徑(名稱)
  • 模式(讀、寫、追加等)

常用模式

  • 'r':讀取(預設)
  • 'w':寫入(覆蓋現有內容)
  • 'a':追加(新增至現有內容)
  • 'x':獨佔建立(如果檔案已存在則失敗)
  • 'b':二進位模式
  • '+':開啟以更新(讀寫)

範例:

file = open("scofield.txt", "w")
登入後複製

在這個例子中,我們創建了一個名為 file 的變量,我們說它應該調用 scofield.txt,其中我們附加“w”來覆蓋其中寫入的任何內容。

寫入檔案
要寫入文件,請使用 write() 方法。

 file = open("scofield.txt", "w")
 file.write("Hello, World!")
 file.close()
登入後複製

完成後關閉文件以釋放系統資源非常重要。更好的做法是使用 with 語句,它會自動關閉檔案。

Python: From Beginners to Pro Part 4

 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)
登入後複製

Python: From Beginners to Pro Part 4

附加到檔案
若要將內容新增至現有文件而不覆蓋,請使用追加模式:

with open("scofield.txt", "a") as file:
    file.write("\nThis is a new line.")
登入後複製

您可以新增至現有文件,而不是總是覆蓋現有文件,如果您有一個正在進行的專案並希望存取先前的工作,這是一個很好的方法。

Python: From Beginners to Pro Part 4

為了充分理解文件處理的下一個方面,我們必須暫停學習並深入研究模組和函式庫。

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' 函數從列表中選擇一個隨機項目。

Python: From Beginners to Pro Part 4

  • 「日期時間」模組:

「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 模組來取得當前日期和時間,並建立一個特定的日期。

Python: From Beginners to Pro Part 4

  • 「數學」模組

「數學」模組提供數學函數。

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

  1. python import random as rnd random_number = rnd.randint(1, 10) ## Python External Libraries

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

Python: From Beginners to Pro Part 4

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.

Python: From Beginners to Pro Part 4

Our response was a 200, which means success; we were able to connect to the server.

Python: From Beginners to Pro Part 4

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.

Python: From Beginners to Pro Part 4

The Python Path

When you import a module, Python looks for it in several locations, collectively known as the Python path. This includes.

  1. The directory containing the script you're running
  2. The Python standard library
  3. Directories listed in the PYTHONPATH environment variable
  4. Site-packages directories where third-party libraries are installed

Understanding the Python path can help you troubleshoot import issues and organize your projects effectively.

Best Practices

  1. Import only what you need: Instead of importing entire modules, import specific functions or classes when possible.
  2. Use meaningful aliases: If you use aliases, make sure they're clear and descriptive.
  3. Keep your imports organized: Group your imports at the top of your file, typically in the order of standard library imports, third-party imports, and then local imports.
  4. Be cautious with 'from module import ***'**: This can lead to naming conflicts and make your code harder to understand.
  5. Use virtual environments: When working on different projects, use virtual environments to manage dependencies and avoid conflicts between different versions of libraries.

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 部落格上找到更多令人興奮的貼文;我們編寫從雲端運算到前端開發、網路安全、人工智慧和區塊鏈的所有技術。

資源

  • 開始使用 Folium
  • Visual Studio Code 的 20 個基本 Python 擴充
  • 使用 Python 進行網頁抓取與資料擷取
  • Python 入門
  • 使用 Folium 和 Python 建立互動式地圖

以上是Python:從初學者到專業人士第 4 部分的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板