Learn Python file backup and recovery technology, so that your data will never be lost!

When performing Python file IO operations, file security and protection are very important. This article mainly introduces the knowledge of file permission management and file backup and recovery in Python.

File permission management

1. The concept and function of file permissions

In Linux and Windows systems, each file has certain permissions, which determine which users can access or modify the file. Usually includes read (r), write (w) and execute (x) three permissions. in:

  • Read permission (r) allows the user to view the file contents.
  • Write permission (w) allows the user to modify the contents of the file.
  • Execute permission (x) allows the user to run executable files.

You can use the chmod command to modify file permissions. For the Linux system, chmod a+x file can add execution permission to all users, and chmod 600 file can set the file so that only the owner of the file can read and write, and other users have no permission.

2. How to set file permissions in Linux and Windows systems

In Python, file permissions can be set through the os module. The os.chmod(path, mode) function can be used to modify the permissions of files or directories, where path is the file path and mode is the permission value. For example, os.chmod("test.txt", 0o777) can set the permissions of the test.txt file to be read, write and execute by everyone.

On Windows, you can use the pywin32 module to set file permissions. The specific implementation method is as follows:

import win32api
import win32con

def set_file_permission(file_path):
    """
    设置文件权限为只读
    """
    # 获取文件属性
    file_attribute = win32api.GetFileAttributes(file_path)
    # 设置文件属性,如果是只读则加上可写标志,否则设置为只读。
    if (file_attribute & win32con.FILE_ATTRIBUTE_READONLY):
        win32api.SetFileAttributes(file_path, win32con.FILE_ATTRIBUTE_NORMAL)
    else:
        win32api.SetFileAttributes(file_path, win32con.FILE_ATTRIBUTE_READONLY)

3. Prevent illegal users from accessing and modifying files

In Python, a file locking mechanism can be used to prevent multiple processes from accessing the same file at the same time. When a process accesses a file, the file can be locked and the lock is not released until the process completes the operation. Other processes cannot access the file while the file is locked.

File locking can be achieved using the flock function. Among them, fcntl.LOCK_EX represents an exclusive lock, and fcntl.LOCK_SH represents a shared lock.

import fcntl

# 独占锁定
def lock_ex(file):
    fcntl.flock(file.fileno(), fcntl.LOCK_EX)

# 共享锁定
def lock_sh(file):
    fcntl.flock(file.fileno(), fcntl.LOCK_SH)

# 解锁
def unlock(file):
    fcntl.flock(file.fileno(), fcntl.LOCK_UN)

Sample code:

import os
import fcntl

def read_file(file_path):
    with open(file_path, 'r') as f:
        lock_sh(f)
        content = f.read()
        unlock(f)
    return content

def write_file(file_path, content):
    with open(file_path, 'w') as f:
        lock_ex(f)
        f.write(content)
        unlock(f)

if __name__ == '__main__':
    file_path = 'test.txt'
    if os.path.exists(file_path):
        print(read_file(file_path))
    else:
        write_file(file_path, 'Hello World!')

File backup and restore

1. The necessity and application scenarios of file backup and recovery

File backup and recovery is very important to prevent data loss or corruption. In practical applications, file backup and recovery are usually used in the following scenarios:

  • Prevent data loss from system crashes;
  • Prevent the deletion or modification of important files by mistake;
  • Back up important data such as databases.

2. How to use Python to implement file backup and recovery functions

The shutil module can be used in Python to implement file backup and recovery functions. The shutil.copy(src, dst) function can copy the src file to the dst directory. The shutil.move(src, dst) function can move the src file to the dst directory. In addition, you can use the os.path.exists(path) function to determine whether a file exists.

Sample code:

import shutil
import os
import time

def backup_file(file_path):
    if os.path.exists(file_path):
        backup_dir = os.path.join(os.path.dirname(file_path), 'backup')
        if not os.path.exists(backup_dir):
            os.mkdir(backup_dir)
        backup_file_name = os.path.basename(file_path) + '_' + \
                           time.strftime('%Y%m%d%H%M%S', time.localtime()) + '.bak'
        backup_file_path = os.path.join(backup_dir, backup_file_name)
        shutil.copy(file_path, backup_file_path)
        return backup_file_path
    else:
        print('File not exists!')
        return None

def restore_file(backup_file_path, target_file_path):
    if os.path.exists(backup_file_path):
        shutil.move(backup_file_path, target_file_path)
        return True
    else:
        print('Backup file not exists!')
        return False

if __name__ == '__main__':
    file_path = 'test.txt'
    backup_file_path = backup_file(file_path)
    print('Backup file path:', backup_file_path)
    restore_file(backup_file_path, file_path)

3. How to realize automatic backup and scheduled backup

Automatic backup and scheduled backup can be implemented using Python's scheduled task library - APScheduler. You can back up files regularly by setting a timer. APScheduler provides a variety of triggers, such as IntervalTrigger, CronTrigger, etc.

Sample code:

import shutil
import os
import time
from apscheduler.schedulers.blocking import BlockingScheduler

def backup_file(file_path):
    if os.path.exists(file_path):
        backup_dir = os.path.join(os.path.dirname(file_path), 'backup')
        if not os.path.exists(backup_dir):
            os.mkdir(backup_dir)
        backup_file_name = os.path.basename(file_path) + '_' + \
                           time.strftime('%Y%m%d%H%M%S', time.localtime()) + '.bak'
        backup_file_path = os.path.join(backup_dir, backup_file_name)
        shutil.copy(file_path, backup_file_path)
        return backup_file_path
    else:
        print('File not exists!')
        return None

def restore_file(backup_file_path, target_file_path):
    if os.path.exists(backup_file_path):
        shutil.move(backup_file_path, target_file_path)
        return True
    else:
        print('Backup file not exists!')
        return False

def job():
    file_path = 'test.txt'
    backup_file_path = backup_file(file_path)
    print('Backup file path:', backup_file_path)

if __name__ == '__main__':
    # 定义定时任务,每10秒执行一次
    scheduler = BlockingScheduler()
    scheduler.add_job(job, 'interval', seconds=10)
    scheduler.start()

The above are the knowledge points and implementation methods of file protection and security in Python IO. By mastering technologies such as file rights management, file locking, file backup and recovery, automatic backup and scheduled backup, you can better protect file security and prevent data loss and damage.

Related Content Expansion: (Technical Frontier)

In the past 10 years, when even traditional enterprises began to digitize on a large scale, we found that in the process of developing internal tools, a large number of pages, scenes, components, etc. were constantly repeated. This repetitive work of reinventing the wheel wasted a lot of time for engineers.

In response to such problems, low-code visualizes certain recurring scenarios and processes into individual components, APIs, and database interfaces, avoiding repeated wheel creation. Greatly improved programmer productivity.

Recommend a software JNPF rapid development platform that programmers should know, adopts the industry-leading SpringBoot micro-service architecture, supports SpringCloud mode, improves the foundation of platform expansion, and meets the needs of rapid system development, flexible expansion, seamless integration and high Comprehensive capabilities such as performance applications; adopting the front-end and back-end separation mode, front-end and back-end developers can work together to be responsible for different sections, saving trouble and convenience.

Free trial official website: https://www.jnpfsoft.com/?csdn

If you haven't understood the low-code technology, you can experience and learn it quickly!

Guess you like

Origin blog.csdn.net/Z__7Gk/article/details/132479450