python 系统学习第四天

关于模块的导入形式

  • import from…
  • import from…
  • import * from …
  • import …as
  • import…as
    #测试代码:
    def test(a,b,c):
    print(“次函数只会在当前模块中运行代码”)
    name==‘main’#代码执行入口
    只会在当前模块中运行代码的时候执行下面代码
    test(“1”,“2” “3”)
    相对路径跟绝对路径
    在这里插入图片描述
    相对路径,同级的时候是可以直接用的,如果用到上级目录会用到 …/ 或./
    绝对路径是可以绝对找到文件,但是可能会比较长
    r‘为转移符

os
在这里插入图片描述

import  os
real_path=os.path.realpath(__file__)#获取当前文件的绝对路径 file 只能获取到当前文件的路径,具体得到模块名
print(real_path)
结果
C:\Users\Administrator\PycharmProjects\untitled3\testing\quanjujubu.py
ppath=os.getcwd()#获取当前工作目录
print(ppath)
结果
C:\Users\Administrator\PycharmProjects\untitled3\testing
file_list=os.listdir(ppath)#罗列当前工作目录下的所有文件名
print(file_list)
结果
['file0408.py', 'geckodriver.log', 'new0408.py', 'newFile0410.py', 'newfile0411.py', ]

file_list=os.listdir(ppath)#罗列当前工作目录下的所有文件名
for file in file_list:#循环判断列表里面是文件还是文件夹
  if os.path.isdir(file): #判断是否为文件目录
      print(file+"是文件夹")
  elif os.path.isfile(file):#判断是否为文件件
      print(file+"是文件")

文件的增加删除

import  os
os.mkdir('在当前目录下新建')
os.rmdir('在当前目录下新建')
目录得一级一级删除,无法越级删除

文件目录的拼接:

print(os.path.join(ppath,"拼接路径"))#拼接路径
print("2"+ppath+"other")
print("3"+ppath+"\other")
结果
C:\Users\Administrator\PycharmProjects\untitled3\testing\拼接路径
2C:\Users\Administrator\PycharmProjects\untitled3\testingother
3C:\Users\Administrator\PycharmProjects\untitled3\testing\other

猜你喜欢

转载自blog.csdn.net/guotianxiu1234/article/details/89305667
今日推荐