python 文件操作的相对路径和绝对路径(windows)

1.相对路径

windows  '.\'表示当前路径

with open(r'.\db\123.txt','w',encoding='utf-8') as f:
    f.write('abc')

 

2.绝对路径

2.1 直接加死绝对路径

with open('c:\db\123.txt','w',encoding='utf-8') as f:
    f.write('abc')

2.2 动态绝对路径

import os,sys
project_path = os.path.dirname(os.path.abspath(__file__)) # 获取当前文件路径的上一级目录
file_path = project_path+r'\db\123.txt' # 拼接路径字符串
with open(file_path,'w',encoding='utf-8') as f:
    f.write('abc')

  

posted on 2018-11-06 00:38  卓某  阅读(15546)  评论(1编辑  收藏  举报

导航