View the file name and file path in Python
- 2020-05-27 06:27:10
- OfStack
View the 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'
>>>
import os
print(os.path.realpath(__file__)) # The path to the current file
print(os.path.dirname(os.path.realpath(__file__))) # Gets the directory from the current file path
print(os.path.basename(os.path.realpath(__file__))) # Gets the file name from the current file path
print(os.listdir(dirname)) # Only the file name and directory name under the directory are displayed, not the files in the subdirectory, the default is the directory where the current file is located
import os
# os.walk() Walk through all the files in the folder
# os.walk() To obtain 3 Set of data (rootdir, dirname,filnames)
def file_path(file_dir):
for root, dirs, files in os.walk(file_dir):
print(root, end=' ') # Current directory path
print(dirs, end=' ') # All subdirectories under the current path
print(files) # All non-directory subfiles in the current directory