Home > Backend Development > Python Tutorial > Python: From Beginners to Pro Part 4

Python: From Beginners to Pro Part 4

王林
Release: 2024-07-24 13:59:51
Original
412 people have browsed it

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")
Copy after login

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()
Copy after login

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!")
Copy after login

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
Copy after login

Example:

with open("scofield.txt", "r") as file:
    content = file.read()
    print(content)
Copy after login

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.")
Copy after login

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)
Copy after login

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)
Copy after login

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)
Copy after login

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)
Copy after login

Import specific functions from a module

from random import randint
random_number = randint(1, 10)
Copy after login

Import all functions from a module (use cautiously)

from random import *
random_number = randint(1, 10)
Copy after login

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())
Copy after login

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")
Copy after login

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)
Copy after login

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")
Copy after login

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.

The open() function is used to open the file. We pass it two arguments: our file_path and the mode "w". The "w" mode stands for write mode, which will create the file if it doesn't exist or overwrite it if it does. Other common modes include "r" for read and "a" for append.

Finally, we use the write() method to put some text into our file. The text "Using os.path.join for file paths" will be written to the file, demonstrating that we've successfully created and written to a file using a path that works on any operating system.

If you like my work and want to help me continue dropping content like this, buy me a cup of coffee.

If you find our post exciting, find more exciting posts on Learnhub Blog; we write everything tech from Cloud computing to Frontend Dev, Cybersecurity, AI, and Blockchain.

Resource

  • Getting started with Folium
  • 20 Essential Python Extensions for Visual Studio Code
  • Using Python for Web Scraping and Data Extraction
  • Getting Started with Python
  • Creating Interactive Maps with Folium and Python

The above is the detailed content of Python: From Beginners to Pro Part 4. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template