在Python中执行文件路径通常有以下几种方法:
使用命令行执行Python文件
python 文件路径.py
例如,如果你有一个名为`example.py`的文件,你可以通过命令行执行它:
python example.py
使用`os`模块
import os获取当前工作目录current_dir = os.getcwd()print(current_dir)构建文件路径folder = "data"file_name = "example.txt"file_path = os.path.join(folder, file_name)print(file_path)执行文件with open(file_path, 'r') as file:content = file.read()print(content)
使用`pathlib`模块 (Python 3.4及以上版本推荐使用):

from pathlib import Path获取当前工作目录current_dir = Path.cwd()print(current_dir)构建文件路径folder = "data"file_name = "example.txt"file_path = Path(folder) / file_nameprint(file_path)执行文件with open(file_path, 'r') as file:content = file.read()print(content)
使用`sys`模块
import sys获取当前工作目录current_dir = os.path.dirname(os.path.realpath(sys.argv))print(current_dir)执行文件with open(sys.argv, 'r') as file:content = file.read()print(content)
以上方法可以帮助你在Python中执行文件路径。请根据你的具体需求选择合适的方法
