本文主要是介绍python之os处理文件和目录的函数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1. 获取当前工作目录
import oscurrent_directory = os.getcwd()
print("Current Directory:", current_directory)
样例输出:
Current Directory: /home/user/project
2. 改变当前工作目录
import osos.chdir('/path/to/new/directory')
print("Changed Directory:", os.getcwd())
样例输出:
Changed Directory: /path/to/new/directory
3. 列出目录中的所有文件和子目录
import osdirectory_contents = os.listdir('/path/to/directory')
print("Directory Contents:", directory_contents)
样例输出:
Directory Contents: ['file1.txt', 'file2.txt', 'subdir']
4. 创建新目录
import osos.mkdir('/path/to/new/directory')
print("Directory Created")
样例输出:
Directory Created
5. 递归创建目录
import osos.makedirs('/path/to/new/directory/with/subdirectories')
print("Directories Created")
样例输出:
Directories Created
6. 删除文件
import osos.remove('/path/to/file')
print("File Deleted")
样例输出:
File Deleted
7. 删除空目录
import osos.rmdir('/path/to/empty/directory')
print("Empty Directory Deleted")
样例输出:
Empty Directory Deleted
8. 递归删除目录
import shutilshutil.rmtree('/path/to/directory')
print("Directory and all its contents deleted")
样例输出:
Directory and all its contents deleted
9. 检查路径是否存在
import ospath_exists = os.path.exists('/path/to/check')
print("Path Exists:", path_exists)
样例输出:
Path Exists: True
10. 检查是否是文件
import osis_file = os.path.isfile('/path/to/check')
print("Is File:", is_file)
样例输出:
Is File: True
11. 检查是否是目录
import osis_directory = os.path.isdir('/path/to/check')
print("Is Directory:", is_directory)
样例输出:
Is Directory: False
12. 获取文件的大小
import osfile_size = os.path.getsize('/path/to/file')
print("File Size:", file_size)
样例输出:
File Size: 1024
13. 获取文件的绝对路径
import osabsolute_path = os.path.abspath('relative/path/to/file')
print("Absolute Path:", absolute_path)
样例输出:
Absolute Path: /home/user/project/relative/path/to/file
14. 分割路径
import ospath, filename = os.path.split('/path/to/file')
print("Path:", path)
print("Filename:", filename)
样例输出:
Path: /path/to
Filename: file
15. 获取文件扩展名
import osfilename, file_extension = os.path.splitext('/path/to/file.txt')
print("Filename:", filename)
print("File Extension:", file_extension)
样例输出:
Filename: /path/to/file
File Extension: .txt
16. 遍历目录树
import osfor root, dirs, files in os.walk('/path/to/directory'):print("Root:", root)print("Directories:", dirs)print("Files:", files)
样例输出:
Root: /path/to/directory
Directories: ['subdir1', 'subdir2']
Files: ['file1.txt', 'file2.txt']
Root: /path/to/directory/subdir1
Directories: []
Files: ['file3.txt']
Root: /path/to/directory/subdir2
Directories: []
Files: ['file4.txt']
好的,继续为你提供剩余的代码示例和样例输出:
17. 组合路径
import oscombined_path = os.path.join('/path/to/directory', 'file.txt')
print("Combined Path:", combined_path)
样例输出:
Combined Path: /path/to/directory/file.txt
这篇关于python之os处理文件和目录的函数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!