Home  >  Article  >  Backend Development  >  How to view file names and file paths in Python

How to view file names and file paths in Python

高洛峰
高洛峰Original
2017-03-24 15:41:011354browse

View file name and file path

>>> import os
>>> url = 'http://images.cnitblog.com/i/311516/201403/020013141657112.png'
>>> filename = os.path.basename(url)
>>> filepath = os.path.dirname(url)
>>> filename 
'020013141657112.png'
>>> filepath
'http://images.cnitblog.com/i/311516/201403'
>>>


(os.path.realpath())    (os.path.dirname(os.path.realpath()))  (os.path.basename(os.path.realpath()))


print(os.listdir(dirname))     # 只显示该目录下的文件名和目录名,不包含子目录中的文件,默认为当前文件所在目录
import os

# os.walk()遍历文件夹下的所有文件
# os.walk()获得三组数据(rootdir, dirname,filnames)
def file_path(file_dir):
    for root, dirs, files in os.walk(file_dir):
        print(root, end=' ')    # 当前目录路径
        print(dirs, end=' ')    # 当前路径下的所有子目录
        print(files)            # 当前目录下的所有非目录子文件

The above is the detailed content of How to view file names and file paths in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn