Python 小项目练习(1)
batch_file_rename.py
__author__ = 'Craig Richards'
__version__ = '1.0'
import argparse
import os
# 批量重命名 # 工作目录, 旧文件, 新文件
def batch_rename(work_dir, old_ext, new_ext):
"""
tHIS will batch rename a group of files in a given directory,
once you pass the current and new extensions
"""
# files: 以列表的形式 列出工作目录的文件 ['0.txt', '2.txt', 'batch_file_rename.py']
# files = os.listdir(work_dir)
# 遍历工作目录的文件
for filename in os.listdir(work_dir):
# Get the file extension
# 分离文件名和扩展名 得到元组
# ('0', '.txt')
# ('2', '.txt')
# ('batch_file_rename', '.py')
split_file = os.path.splitext(filename)
# Unpack tuple element
# 将元组各值赋值给两个变量
# 文件名, 文件格式
root_name, file_ext = split_file
# Start of the logic to check the file extensions, if old_ext = file_ext
# 如果当前文件的格式等于旧文件的格式
if old_ext == file_ext:
# Returns changed name of the file with new extention
# 拼接新文件名
newfile = root_name + new_ext
# Write the files
# 重命名文件 ( 1.原文件名 2.新文件名 )
os.rename(
# 拼接路径和文件名
os.path.join(work_dir, filename),
os.path.join(work_dir, newfile)
)
print("rename is done!")
print(os.listdir(work_dir))
# 获取解析
def get_parser():
# 使用argparse方法的ArgumentParser生成实例
# 更改工作目录中文件的扩展名
parser = argparse.ArgumentParser(description='change extension of files in a working directory')
# 工作目录 , 元变量
parser.add_argument('work_dir', metavar='WORK_DIR', type=str, nargs=1,
help='the directory where to change extension')
parser.add_argument('old_ext', metavar='OLD_EXT', type=str, nargs=1, help='old extension')
parser.add_argument('new_ext', metavar='NEW_EXT', type=str, nargs=1, help='new extension')
return parser
def main():
"""
This will be called if the script is directly invoked.
:return:
"""
# 增加命令行参数
# 将get_parser()获取的值存入parser中
parser = get_parser()
# vars()函数返回对象object的属性和属性值的字典对象
args = vars(parser.parse_args())
# Set the variable work_dir with the first argument passed
# 设置变量work_dir 并传递第一个参数
work_dir = args['work_dir'][0]
# Set the variable old_ext with the second argument passed
# 设置变量old_ext 并传递第二个参数
old_ext = args['old_ext'][0]
# 如果old_ext的第一个参数不是'.'
if old_ext[0] != '.':
# 给old_ext的前面加个'.'
old_ext = '.' + old_ext
# Set the variable new_ext with the third argument passed
new_ext = args['new_ext'][0]
if new_ext[0] != '.':
new_ext = '.' + new_ext
batch_rename(work_dir, old_ext, new_ext)
if __name__ == '__main__':
main()
create_dir_if_not_there.py
import os
MESSAGE = 'The directory already exists.'
TESTDIR = 'testdir'
try:
# 扩展用户设置的主目录 # C:\Users\PC1
home = os.path.expanduser("~") # Set the variable home by expanding the user's set home directory
print(home) # Print the location
# 如果不存在
if not os.path.exists(os.path.join(home, TESTDIR)):
# 安全的创建一个全路径(安全拼接home路径和文件名)
os.makedirs(os.path.join(home, TESTDIR)) # If not create the directory, inside their home directory
else:
print(MESSAGE)
except Exception as e:
print(e)
posted on 2020-07-27 22:34 sunnywillow 阅读(155) 评论(0) 编辑 收藏 举报