赞
踩
在使用python的时候总会遇到路径切换的使用情况,如想从文件夹test下的test.py
调用data文件夹下的data.txt
文件:
一种方法可以在data文件下加入__init__.py
然后在test.py
中import data
就可以调用data.txt
文件;
- .
- └── folder
- ├── data
- │ └── data.py
- └── test
- └── test.py
另一种方法可以借助python os模块的方法对目录结构进行操作,下面就说一下这种方式的使用:
- #data.py
-
-
- import os
- import sys
- print('***获取当前目录***')
- print(os.getcwd())
- print(os.path.abspath(os.path.dirname(__file__)))
-
- print('***获取上级目录***')
- print(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
- print(os.path.abspath(os.path.dirname(os.getcwd())))
- print(os.path.abspath(os.path.join(os.getcwd(), "..")))
- tmppath = os.path.abspath(os.path.join(os.getcwd(), ".."))
-
- print('***获取库目录***')
- tmppath= tmppath+"\\test"
- print(tmppath)
-
- print('***获取上上级目录***')
- print(os.path.abspath(os.path.join(os.getcwd(), "../..")))
-
- sys.path.insert(0,tmppath)
- print(sys.path)
-
-
- import test
-
-
- '''
- Tab =[]
- Tab.append("aaa")
- print(Tab.index("aaa"))
- Tab.append("aabb)
- Tab.append("cc")
- print(Tab.index("dd"))
- cc = list(enumerate(Tab))
- print("Id ","name")
- print(cc[0][0],": ",cc[0][1])
- print(cc[1][0],": ",cc[1][1])
- print(cc[2][0],": ",cc[2][1])
- #print()
- Tab1 = cc
- print(len(cc))
- print(len(cc[0]))
- print('')
- print('')
- '''
- '''
- def cleantxt(inputfile):
- with open(inputfile, "w", encoding="utf-8") as f_clean_w :
- f_clean_w.write('')
- '''
- def SaveModTab(inputfile,Tab):
- Tab = list(enumerate(Tab))
- with open(inputfile, "w", encoding="utf-8") as f_w:
- tmp ="zzz:"
- f_w.write(tmp+'\n')
- print(tmp)
- tmp =" zzzId zzz_Name"
- f_w.write(tmp+'\n')
- print(tmp)
- for i in range(0,len(Tab)):
- tmp = " "+str(Tab[i][0]) +" "+str(Tab[i][1])
- print(tmp)
- f_w.write(tmp+'\n')
-
-
-
-
- inputfile = 'Tab.txt'
- Tab =[]
- Tab.append("aaa")
-
- print(Tab.index("aaa"))
- Tab.append("bb")
- Tab.append("cc")
- Tab.append("dd")
-
- #cleantxt(inputfile)
- Tab(inputfile,Tab)
-
- test.primt("22222")
-
-
-
可以以下这种: 都不需要__init__.py
- ''' 方法1
- print('***获取库目录***')
- tmppath= tmppath+"/aa"
- print(tmppath)
- print('***获取上上级目录***')
- print(os.path.abspath(os.path.join(os.getcwd(), "../..")))
- sys.path.insert(0,tmppath)
- print(sys.path)
- import test
- '''
-
-
- #方法2 (from 不能使用多级目录bb/cc/aa)
-
- print('***获取库目录***')
- #tmppath= tmppath+"/aa"
- print(tmppath)
-
- print('***获取上上级目录***')
- print(os.path.abspath(os.path.join(os.getcwd(), "../..")))
-
- sys.path.insert(0,tmppath)
- print(sys.path)
-
- from aa import test
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。