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')

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM