获取准确路径目录
20211207
https://www.runoob.com/w3cnote/python-check-whether-a-file-exists.html
import os.path
os.path.isfile(fname)
https://blog.csdn.net/qq_21240643/article/details/99412409
# 刪除文件
os.remove('D:\\ss\\s\\1.txt') # 刪除文件
判斷路徑是否存在并刪除
20201226
只需使用globals()
globals() - 返回一個(gè)代表當(dāng)前全局??符號(hào)表的字典。這總是當(dāng)前模塊的目錄(在函數(shù)或方法內(nèi)部,這是定義它的模塊,而不是從中調(diào)用它的模塊)。
import sys
sys.modules[name]
當(dāng)前模塊信息
從某個(gè)文件中除了可以直接import 某個(gè)模塊 py 文件
還可以直接引用一個(gè)模塊(init)中的函數(shù) 不用顯式的寫出init
相當(dāng)于把當(dāng)前路徑 datasets 文件夾本身作為一個(gè)模塊來引用了
20201209
os.path.split(os.path.realpath(file))[0]
https://blog.csdn.net/kyle1314608/article/details/110930515
獲取當(dāng)前路徑
os.path.dirname(edt.file)
20201125
一、獲取當(dāng)前路徑
1、使用sys.argv[0]
import sys
print sys.argv[0]
#輸出
#本地路徑
2、os模塊
復(fù)制代碼
import os
print os.getcwd() #獲取當(dāng)前工作目錄路徑
print os.path.abspath(’.’) #獲取當(dāng)前工作目錄路徑
print os.path.abspath(‘test.txt’) #獲取當(dāng)前目錄文件下的工作目錄路徑
print os.path.abspath(’…’) #獲取當(dāng)前工作的父目錄 !注意是父目錄路徑
print os.path.abspath(os.curdir) #獲取當(dāng)前工作目錄路徑
3、改變當(dāng)前目錄
1) 使用: os.chdir(path)。
比如, 如果當(dāng)前目錄在 ‘E:’ 下面, 然后進(jìn)入E 下面的files 文件 可以使用 os.chdir(E:\files).
之后,使用比如 test1 = open(‘file1.txt’), 打開的文件會(huì)是在這個(gè) ‘E:\files’ 目錄下的文件,而不是 ‘E’ 下的文件。
4、組合路徑返回
os.path.join(‘file1’,‘file2’,‘file3’)
合并得到路徑 file1/file2/file3
print os.path.join(‘E:’, ‘file1’, ‘file2’)
E:/file1/file2print os.path.join(’/home’, ‘/home/file1/’, ‘/home/file1/file2/’)
/home/file1/file2/
import os
root = os.getcwd() #獲得當(dāng)前路徑 /home/dir1
print root
#輸出
#/home/dir1
name = “file1” #定義文件名字
print(os.path.join(root, name)) #合并路徑名字和文件名字,并打印
#輸出
#/home/dir1/file1
二、獲得當(dāng)前目錄下所有文件
1. os.walk() 用于在目錄樹種游走輸出目錄中的文件名字,向上或下;
語法
os.walk(top[, topdown=True[, οnerrοr=None[, followlinks=False]]])
參數(shù):
top – 根目錄下的每一個(gè)文件夾(包含它自己), 產(chǎn)生3-元組 (dirpath, dirnames, filenames)【文件夾路徑,
文件夾名字, 文件名】。
topdown --可選,為True或者沒有指定, 一個(gè)目錄的的3-元組將比它的任何子文件夾的3-元組先產(chǎn)生 (目錄自上而下)。
如果topdown為 False, 一個(gè)目錄的3-元組將比它的任何子文件夾的3-元組后產(chǎn)生 (目錄自下而上)。
onerror – 可選,是一個(gè)函數(shù); 它調(diào)用時(shí)有一個(gè)參數(shù), 一個(gè)OSError實(shí)例。報(bào)告這錯(cuò)誤后,繼續(xù)walk,或者拋出exception終止walk。
followlinks – 設(shè)置為 true,則通過軟鏈接訪問目錄。
import os
root = os.getcwd()
def file_name(file_dir):
for root, dirs, files in os.walk(file_dir):
print “-----------”
print root #os.walk()所在目錄
print dirs #os.walk()所在目錄的所有目錄名
print files #os.walk()所在目錄的所有非目錄文件名
print " "
file_name(root)
ptbert 和 train.txt的上上層文件夾data在一個(gè)目錄里面
os.path.join 補(bǔ)充到與當(dāng)前運(yùn)行腳步相同的路徑下
比如這里的 data_dir=‘data/hotel/’
https://www.cnblogs.com/qiumingcheng/p/7760215.html
import a_module
print a_module.file
上述代碼將范圍 .pyc 文件被加載的路徑,如果需要跨平臺(tái)解決方案,可用下面代碼:
import os
path = os.path.dirname(amodule.file)
獲取導(dǎo)入模塊路徑
cur = ‘/’.join(os.path.abspath(file).split(’\’)[:-1])
獲取當(dāng)前路徑
獲得準(zhǔn)確路徑的方法 os.getcwd()是獲得上層目錄
不停嵌套 不停的獲得上層目錄
根目錄
判斷是否是路徑
獲取當(dāng)前文件所在的父路徑
https://www.cnblogs.com/guohu/p/11281263.html 路徑
總結(jié)
- 上一篇: 使用Pycharm给Python程序传递
- 下一篇: 打标遗留的问题