How to view file names and file paths in Python

迷茫
Release: 2017-03-25 11:07:26
Original
2302 people have browsed it

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'
 >>>
Copy after login
 import os
 print(os.path.realpath(__file__))    # 当前文件的路径
 print(os.path.dirname(os.path.realpath(__file__)))  # 从当前文件路径中获取目录
 print(os.path.basename(os.path.realpath(__file__))) # 从当前文件路径中获取文件名
Copy after login
print(os.listdir(dirname))     # 只显示该目录下的文件名和目录名,不包含子目录中的文件,默认为当前文件所在目录
Copy after login
 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)            # 当前目录下的所有非目录子文件
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!