# encoding=utf-8
import sys,os,time
sys.path.append(os.path.abspath(os.path.split(os.path.abspath(__file__))[0]+"\\.."))
print({"sys.path":sys.path})
# {'sys.path': ['E:\\Python\\argv_getopt_argpara','E:\\Python']}
# E:\\Python\\argv_getopt_argpara:当前文件执行路径
# E:\\Python:人为指定搜索路径
# 解析理解如下:
file_abspath = os.path.abspath(__file__)
print({"file_abspath":file_abspath})
#{'file_abspath': 'E:\\Python\\argv_getopt_argpara\\argv.py'}
cur_file_path, file_name = os.path.split(file_abspath)
print({"cur_file_path":cur_file_path, "file_name":file_name})
# {'cur_file_path': 'E:\\Python\\argv_getopt_argpara', 'file_name': 'argv.py'}
cur_file_parent_path = os.path.abspath(cur_file_path + "\\..")
print({"cur_file_parent_path":cur_file_parent_path})
# {'cur_file_parent_path': 'E:\\Python'}
# 1,获取当前执行文件所在目录相对路径
cur_exec_file_path = os.path.dirname(__file__)
print({"cur_exec_file_path":cur_exec_file_path})
# {'cur_exec_file_path': ''}
tm_year, tm_mon, tm_mday, _, _, _, _, _, _ = time.localtime()
csv_name = os.path.join(cur_exec_file_path, "{}-{}-{}-test.csv".format(str(tm_year).zfill(4), str(tm_mon).zfill(2), str(tm_mday).zfill(2)))
print({"csv_name":csv_name})
# {'csv_name': '2022-04-23-test.csv'}
代码实现:
# -*- coding:utf-8 -*-
from pathlib import Path
from os.path import abspath
pathString = """
D:\Edisk\python\BatchRename
D:\BaiduNetdiskDownload\day18
D:\BaiduNetdiskDownload\day19_多线程
"""
def stringToPath(s):
print("****************abspath(s)******************")
print('abspath(s)原始字符串:', s)
print('abspath(s)绝对路径为:', [abspath(s)])
print('abspath(s)绝对路径为:', abspath(s))
print("\n****************Path(s)*********************")
path = Path(s)
print('Path(s)转为路径后:', [path])
print('Path(s)转为路径后:', path)
print('Path(s)再转回字符串:', [str(path)])
print('Path(s)再转回字符串:', str(path))
if __name__ == '__main__':
paths = pathString.split('\n')
for path in paths[1:-1]:
print("="*40)
stringToPath(path)
print("\n")
打印结果: