importos# 获取当前工作路径current_path=os.getcwd()print(f"当前工作路径是:{current_path}")# 打开并读取文本文件file_name="example.txt"file_path=os.path.join(current_path,file_name)try:withopen(file_path,'r',encoding='utf-8')asfile:content=file.read()print("文件内容:")print(content)excep...
importos# 1. 确定当前工作目录current_directory=os.getcwd()# 2. 拼接相对路径relative_path=os.path.join(current_directory,"file.txt")# 3. 创建文件file_path=os.path.join(current_directory,"file.txt")withopen(file_path,"w")asfile:file.write("Hello, Python!") 1. 2. 3. 4. 5. 6. 7...
path.join(current_dir, relative_path) # 现在可以安全地使用absolute_path了 使用pathlib模块:pathlib是Python 3.4及以上版本中引入的一个更现代、更直观的文件和目录处理库。它提供了Path类,可以方便地处理路径相关的操作。例如: from pathlib import Path # 创建Path对象 p = Path('data/file.txt') # 获取绝...
#新版python3.7中pathlib.Path()可以直接 #获取文件夹下的文件路径,不需要os.path from pathlib import Path #cwd获取当前工作目录 current_working_directory = Path.cwd() print(current_working_directory)输出结果为:/Users/admin/Documents/python语言程序设计/pw_auto 2、合并路径 通过joinpath()方法把路径和...
('').print('os.path.basename(__file__) =', os.path.basename(__file__))print('os.path.basename(path1) =', os.path.basename(path1))print('os.path.basename(path2) =', os.path.basename(path2))#Return a string representing the current working directory.print('os.getcwd() =', ...
import osdir_path = "/my/directory"for root, dirs, files in os.walk(dir_path): for file in files: file_path = os.path.join(root, file) print(file_path)5. 使用os.path.join()函数可以连接多个路径组件,生成一个完整的文件路径。这个函数会根据操作系统的不同自动选择合适的路径分隔...
print(“缓存文件路径:”, os.path.join(folder, filename)) “` 在上面的示例代码中,我们定义了一个 `save_cache_file()` 函数,它接受三个参数:数据、文件夹路径和文件名。函数首先检查文件夹是否存在,如果不存在则创建。然后,使用 `os.path.join()` 函数构建缓存文件的完整路径。最后,将数据写入文件。打...
importcsvcsv_file_path='example.csv'# 读取CSV文件withopen(csv_file_path,'r')ascsvfile:csv_reader=csv.reader(csvfile)forrowincsv_reader:print(row) 2.3 读取JSON文件 使用内置的json模块来读取JSON格式的文件。 importjsonjson_file_path='example.json'# 读取JSON文件withopen(json_file_path,'r')as...
path = os.path.join("folder", "file.txt")错误处理: 在切换目录时,可能会发生一些错误,如权限不足或目标路径无效。要处理这些错误,你可以使用 try...except 块来捕获异常并采取适当的措施。代码 try:os.chdir(target_directory)exceptFileNotFoundError:print(f"目标目录 {target_directory} 不存在.")exc...
os.path.join('output', 'pretext.xlsx')output output\pretext.xlsx 3.确认某文件夹或者是文件是否...