使用Python进行文件操作和路径管理
在Python中,我们可以使用内置的open()
函数进行文件操作。以下是一些基本的操作:
打开文件:
file = open('filename.txt', 'r') # 以读模式打开
写入文件:
file.write('Hello, World!') # 向文件写入内容
file.close() # 关闭文件,释放资源
读取文件内容:
content = file.read() # 一次性读取所有内容
print(content) # 打印读取的内容
文件路径管理:
使用
os
模块的函数处理路径:import os
# 获取当前工作目录
current_dir = os.getcwd()
# 创建新目录
new_dir_path = 'new_directory'
if not os.path.exists(new_dir_path)):
os.mkdir(new_dir_path)
# 移动文件或目录
file_to_move = 'filename.txt'
move_file_path = os.path.join(current_dir, 'moved_files'))
if os.path.isfile(file_to_move)):
os.rename(os.path.join(current_dir, file_to_move))), os.path.join(move_file_path, file_to_move)))
这只是一个基本的例子,Python的文件操作和路径管理功能非常丰富。
还没有评论,来说两句吧...