python工作目录

# -*- coding: UTF-8 -*-
import os
import sys

def print_directory_contents(path):
    for item in os.listdir(path):
        item_path = os.path.join(path, item)
        if os.path.isdir(item_path):
            print("目录:", item)
        else:
            print("文件:", item)

if(len(sys.argv)<2):
    raise "len err"
directory_path = sys.argv[1]

print_directory_contents(dirtest)



current_dir = os.getcwd()
print("当前调用路径:", current_dir)


'''
E:\codeTest\testpy\testDir.py   // py文件路径
E:\codeTest\testDir.bat         // bat文件去调用testDir.py
E:\codeTest\pythonTest          // 测试文件夹


调用
1.python testDir.py ".//pythonTest" 会报错,因为当前目录下没有pythonTest目录
2.python .\testpy\testDir.py ".\pythonTest" 正确

'''

python的工作目录是以调用python文件的方式决定

1.比如直接在包含py文件的同目录下,使用命令行中调用,那么工作目录是当前目录

2.使用bat脚本调用,指定了py文件的路径,那么工作目录是bat所在的目录

  • 使用 os.chdir() 函数可以显式地更改工作目录。调用该函数后,工作目录将变为指定的目录。

 

posted @ 2024-02-28 19:45  乐swap火  阅读(17)  评论(0编辑  收藏  举报