linux

Linux使用Python如何管理文件系统

小樊
81
2024-11-30 20:03:52
栏目: 编程语言

在Linux中,你可以使用Python的内置库osshutil来管理文件系统

  1. 创建目录:
import os

directory_name = "new_directory"

# 检查目录是否已存在
if not os.path.exists(directory_name):
    os.makedirs(directory_name)
    print(f"{directory_name} created.")
else:
    print(f"{directory_name} already exists.")
  1. 删除目录:
import shutil

directory_name = "new_directory"

# 检查目录是否存在
if os.path.exists(directory_name):
    shutil.rmtree(directory_name)
    print(f"{directory_name} deleted.")
else:
    print(f"{directory_name} does not exist.")
  1. 复制文件:
import shutil

source_file = "source_file.txt"
destination_file = "destination_file.txt"

if os.path.exists(source_file):
    shutil.copy2(source_file, destination_file)
    print(f"{source_file} copied to {destination_file}.")
else:
    print(f"{source_file} does not exist.")
  1. 移动文件:
import os

source_file = "source_file.txt"
destination_file = "destination_file.txt"

if os.path.exists(source_file):
    os.rename(source_file, destination_file)
    print(f"{source_file} moved to {destination_file}.")
else:
    print(f"{source_file} does not exist.")
  1. 读取文件内容:
with open("file.txt", "r") as file:
    content = file.read()
    print(content)
  1. 写入文件内容:
file_name = "file.txt"
content = "Hello, World!"

with open(file_name, "w") as file:
    file.write(content)

这些示例展示了如何使用Python在Linux中管理文件系统的基本操作。你可以根据需要扩展这些示例以执行更复杂的文件操作。

0
看了该问题的人还看了