frompathlibimportPathfile_path=Path(__file__).resolve()dir_path=file_path.parentprint("The current file is at: "+str(file_path))print("The directory of the current file is at: "+str(dir_path)) Python Copy 输出结果:
In this example, we import theosmodule and use theos.getcwd()function to print the current directory. The output will be the path of the directory where your Python script is running. This is a basic way to get the current directory in Python, but there’s much more to learn about file...
The os.getcwd() retrieves the absolute path of the directory where the script is running. This method is useful for checking the working directory. Method 2: Using Path.cwd() to Find Directory in Python Python’s pathlib module provides an efficient way to get the current directory and retu...
>>>frompathlibimportPath>>>Path(r"C:\Users\philipp\realpython\file.txt")WindowsPath('C:/Users/philipp/Desktop/realpython/file.txt') # WindowsPosixPath('/home/philipp/Desktop/realpython/file.txt') # LinuxPosixPath('/Users/philipp/Desktop/realpython/file.txt') # macOS 这些步骤创建了一个对象。
# f 是一个文件对象 (file object) print(f"文件 '{ <!-- -->file_path_text}' 已在文本写入模式下打开,编码为 UTF-8。")# 中文解释:打印文件打开状态信息 f.write("你好,世界! ")# 中文解释:向文件写入字符串 "你好,世界!" 并换行
new_path = os.path.join('archive', file_name) shutil.move(file_name, new_path) 而且,由于不同的操作系统使用的分隔符不同,使用字符串拼接路径就容易出现问题。 有了pathlib,使得上述的问题变得更加轻松,pathlib创建的Path对象,可以直接通过正斜杠运算符/连接字符串生成新的对象。
cwd().glob("*.txt"): new_path = Path("archive") / file_path.name file_path.replace(new_path) Just as in the first example, this code finds all the text files in the current directory and moves them to an archive/ subdirectory. However, with pathlib, you accomplish these tasks ...
print(f"Home directory: {Path.home()}") The example prints the current working directory and the home directory. $ cwd_home.py Current directory: C:\Users\Jano\Documents\pyprogs\pathlib Home directory: C:\Users\Jano Python pathlib current file ...
pathlib 是Python内置库,Python 文档给它的定义是:The pathlib module – object-oriented filesystem paths(面向对象的文件系统路径)。pathlib 提供表示文件系统路径的类,其语义适用于不同的操作系统。 1. pathlib模块下Path类的基本使用 代码语言:txt AI代码解释 ...
from pathlib import Path work_dir = Path.cwd() print(work_dir) The program prints the current working directory withPath.cwd. Get current working directory with os.path The__file__is a special Python build-in variable which contains the path to the currently running script. Since Python 3.9...