1、获取当前文件路径:

import os
from pathlib import Path

print(os.path.abspath(__file__))
print(Path(__file__))
#输出
C:\Users\Owner\Desktop\sd.py
C:\Users\Owner\Desktop\sd.py

2、获取某一文件夹下文件目录

import os
from pathlib import Path

file=r'C:\Users\Owner\Desktop\file'

print(os.listdir(file))

print(Path(file).iterdir()) 

for file in Path(file).iterdir():
    print(file)
#输出
['1.txt', '2.txt', '3.txt', '4.txt', '5.txt', '6.txt', 'dir']

<generator object Path.iterdir at 0x00000233CDF7DDC8>

C:\Users\Owner\Desktop\file\1.txt
C:\Users\Owner\Desktop\file\2.txt
C:\Users\Owner\Desktop\file\3.txt
C:\Users\Owner\Desktop\file\4.txt
C:\Users\Owner\Desktop\file\5.txt
C:\Users\Owner\Desktop\file\6.txt
C:\Users\Owner\Desktop\file\dir

3、获取父目录

import os
from pathlib import Path

file=r'C:\Users\Owner\Desktop\file'

print(file.split('\\')[-2])

print(Path(file).parent)

print(Path(file).parents)
for path in Path(file).parents:
     print(path)
#输出
Desktop
C:\Users\Owner\Desktop
<WindowsPath.parents>
C:\Users\Owner\Desktop
C:\Users\Owner
C:\Users
C:\

4、获取子目录文件

import os
from pathlib import Path

dir=r'C:\Users\Owner\Desktop\file'

file=os.path.join(dir,'1.txt')
print(file)

file=Path(dir) / '1.txt'
print(file)
#输出
C:\Users\Owner\Desktop\file\1.txt
C:\Users\Owner\Desktop\file\1.txt

5、创建目录

import os
from pathlib import Path

dir=r'C:\Users\Owner\Desktop\file'

file=os.path.join(dir,'test')
if not os.path.exists(file):
    os.makedirs(file)
    
file=Path(dir) / 'test'
file.mkdir(parents = True, exist_ok = True)

print("Done!")
#输出
Done!
Categories: Python

0 Comments

Leave a Reply

Your email address will not be published.