python实现文件和目录管理
- categories
批量重命名文件
import os
for filename in os.listdir('.'):
os.rename(filename, filename.replace('old', 'new'))
查找大文件
import os
for root, dirs, files in os.walk('.'):
for name in files:
if os.path.getsize(os.path.join(root, name)) > 1024 * 1024: # 大于1MB
print(os.path.join(root, name))
创建目录结构
import os
os.makedirs('dir/subdir/subsubdir', exist_ok=True)
删除空目录
import os
for root, dirs, files in os.walk('.', topdown=False):
for name in dirs:
dir_path = os.path.join(root, name)
if not os.listdir(dir_path):
os.rmdir(dir_path)
复制文件
import shutil
shutil.copy('source.txt', 'destination.txt')
移动文件
import shutil
shutil.move('source.txt', 'destination.txt')
读取文件内容
with open('file.txt', 'r') as file:
content = file.read()
写入文件内容
with open('file.txt', 'w') as file:
file.write('Hello, World!')
追加文件内容
with open('file.txt', 'a') as file:
file.write('\nAppend this line.')
检查文件是否存在
import os
if os.path.exists('file.txt'):
print("File exists.")
else:
print("File does not exist.")
comment:
- Valine
- LiveRe
- ChangYan