首页  >  文章  >  后端开发  >  Python:从初学者到专业人士第 4 部分

Python:从初学者到专业人士第 4 部分

王林
王林原创
2024-07-24 13:59:51294浏览

文件处理:学习读取和写入文件

文件处理对于任何程序员来说都是一项至关重要的技能。每个开发者都应该能够访问外部来源的数据并与之交互,并实现计算和存储。

文件用于在磁盘上存储数据。它们可以包含文本、数字或二进制数据。在 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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn