Python: Dari Pemula hingga Pro Bahagian 4

王林
Lepaskan: 2024-07-24 13:59:51
asal
154 人浏览过

File Handling: Learn to read from and write to files

File handling is a crucial skill for any programmer. every developer should be able to access and interact with data from external sources and implement calculations and storage.

Files are used to store data on disk. They can contain text, numbers, or binary data. In Python, we use built-in functions and methods to work with files.

To open a file, we use the open() function. It takes two main arguments:

  • The file path (name)
  • The mode (read, write, append, etc.)

Common modes

  • 'r': Read (default)
  • 'w': Write (overwrites existing content)
  • 'a': Append (adds to existing content)
  • 'x': Exclusive creation (fails if file already exists)
  • 'b': Binary mode
  • '+': Open for updating (reading and writing)

Example:

file = open("scofield.txt", "w")
Salin selepas log masuk

In this example, we create a variable called file, and we said it should call scofield.txt, in which we append the “w” to overwrite whatever is written inside it.

Writing to Files
To write to a file, use the write() method.

 file = open("scofield.txt", "w")
 file.write("Hello, World!")
 file.close()
Salin selepas log masuk

It's important to close the file after you're done to free up system resources. A better practice is to use a with statement, which automatically closes the file.

Python: From Beginners to Pro Part 4

 with open("scofiedl.txt", "w") as file:
    file.write("Hello, World!")
Salin selepas log masuk

After overwriting what is inside, we wrote the above code but made it shorter, using the with open command closes scofield.txt.

Reading from Files
You can use several methods to read from a file.

read(): Reads the entire file
readline(): Reads a single line
readlines(): Reads all lines into a list
Salin selepas log masuk

Example:

with open("scofield.txt", "r") as file:
    content = file.read()
    print(content)
Salin selepas log masuk

Python: From Beginners to Pro Part 4

Appending to Files
To add content to an existing file without overwriting, use the append mode:

with open("scofield.txt", "a") as file:
    file.write("\nThis is a new line.")
Salin selepas log masuk

You can add to the existing file instead of always overwriting existing files, which is a good approach if you have an ongoing project and want access to previous work.

Python: From Beginners to Pro Part 4

To fully understand this next aspect of file handling, we must pause our learning and take a deep dive into Modules and Libraries.

One of the key features that makes Python so versatile and powerful is its extensive ecosystem of modules and libraries. These tools allow you to extend Python's functionality, making complex tasks simpler and enabling you to write more efficient and powerful programs.

What are Modules and Libraries?
At its core, a module in Python is simply a file containing Python code. It can define functions, classes, and variables you can use in your programs. A library, on the other hand, is a collection of modules. Think of modules as individual tools, while libraries are toolboxes containing multiple related tools.

The main purpose of modules and libraries is to promote code reusability. Instead of writing everything from scratch, you can use pre-written, tested code to perform common tasks. This saves time and reduces the chance of errors in your programs.

Built-in Modules
Python comes with a set of built-in modules that are part of the standard library. These modules are available in every Python installation, providing a wide range of functionality out of the box. Let's explore a few examples.

  • The 'random' Module

The 'random' module is used for generating random numbers. Here's how you can use it:

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)
Salin selepas log masuk

In this example, we first import the random module. Then we use its randint function to generate a random integer and its 'choice' function to select a random item from a list.

Python: From Beginners to Pro Part 4

  • The 'datetime' Module:

The 'datetime' module provides classes for working with dates and times:

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)
Salin selepas log masuk

Here, we use the datetime module to get the current date and time, and to create a specific date.

Python: From Beginners to Pro Part 4

  • The 'math' Module

The 'math' module provides mathematical functions.

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)
Salin selepas log masuk

This example demonstrates using the 'math' module to perform mathematical calculations.

Importing Modules
There are several ways to import modules in Python:

Import the entire module

import random
random_number = random.randint(1, 10)
Salin selepas log masuk

Import specific functions from a module

from random import randint
random_number = randint(1, 10)
Salin selepas log masuk

Import all functions from a module (use cautiously)

from random import *
random_number = randint(1, 10)
Salin selepas log masuk

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())
Salin selepas log masuk

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")
Salin selepas log masuk

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)
Salin selepas log masuk

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")
Salin selepas log masuk

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: Dari Pemula hingga Pro Bahagian 4的详细内容。更多信息请关注PHP中文网其他相关文章!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!