Hướng dẫn how do you separate a filename from the path in python? - làm cách nào để tách tên tệp khỏi đường dẫn trong python?

Đây là một giải pháp chỉ có regex, dường như hoạt động với bất kỳ đường dẫn hệ điều hành nào trên bất kỳ hệ điều hành nào.

Không cần mô -đun khác, và không cần tiền xử lý:

import re

def extract_basename[path]:
  """Extracts basename of a given path. Should Work with any OS Path on any OS"""
  basename = re.search[r'[^\\/]+[?=[\\/]?$]', path]
  if basename:
    return basename.group[0]


paths = ['a/b/c/', 'a/b/c', '\\a\\b\\c', '\\a\\b\\c\\', 'a\\b\\c',
         'a/b/../../a/b/c/', 'a/b/../../a/b/c']

print[[extract_basename[path] for path in paths]]
# ['c', 'c', 'c', 'c', 'c', 'c', 'c']


extra_paths = ['C:\\', 'alone', '/a/space in filename', 'C:\\multi\nline']

print[[extract_basename[path] for path in extra_paths]]
# ['C:', 'alone', 'space in filename', 'multi\nline']

Cập nhật:

Nếu bạn chỉ muốn một tên tệp tiềm năng, nếu có [nghĩa là,

print[os.sep]
# /

print[os.sep is os.path.sep]
# True
5 là một DIR và
print[os.sep]
# /

print[os.sep is os.path.sep]
# True
6] cũng vậy, hãy thay đổi Regex thành:
print[os.sep]
# /

print[os.sep is os.path.sep]
# True
7. Đối với "Regex bị thách thức", điều này làm thay đổi hướng đi về phía trước tích cực đối với một loại chém nào đó đối với một cái nhìn phía trước tiêu cực, khiến các đường dẫn kết thúc bằng việc chém nói không trả lại gì thay vì thư mục phụ cuối cùng trong tên đường dẫn. Tất nhiên không có gì đảm bảo rằng tên tệp tiềm năng thực sự đề cập đến một tệp và đối với
print[os.sep]
# /

print[os.sep is os.path.sep]
# True
8 hoặc
print[os.sep]
# /

print[os.sep is os.path.sep]
# True
9 đó sẽ cần phải được sử dụng.

Điều này sẽ phù hợp như sau:

/a/b/c/             # nothing, pathname ends with the dir 'c'
c:\windows\         # nothing, pathname ends with the dir 'windows'
c:hello.txt         # matches potential filename 'hello.txt'
~it_s_me/.bashrc    # matches potential filename '.bashrc'
c:\windows\system32 # matches potential filename 'system32', except
                    # that is obviously a dir. os.path.is_dir[]
                    # should be used to tell us for sure

Regex có thể được kiểm tra ở đây.

Trong Python, bạn có thể lấy tên tệp [tên cơ sở], tên thư mục [thư mục] và phần mở rộng từ chuỗi đường dẫn hoặc tham gia các chuỗi để tạo chuỗi đường dẫn với mô -đun

filepath = './dir/subdir/filename.ext'
0 trong thư viện tiêu chuẩn.

  • Os.Path - Thao tác tên đường dẫn phổ biến - Tài liệu Python 3.9.1RC1

Bài viết này mô tả các nội dung sau đây.

  • Sự khác biệt về phân tách đường dẫn bằng hệ điều hành
  • Nhận tên tệp [basename] từ một đường dẫn:
    filepath = './dir/subdir/filename.ext'
    
    1
    • Tên tệp với phần mở rộng
    • Tên tệp mà không cần mở rộng
  • Lấy tên thư mục [thư mục] từ một đường dẫn:
    filepath = './dir/subdir/filename.ext'
    
    2
  • Nhận cặp tệp và tên thư mục:
    filepath = './dir/subdir/filename.ext'
    
    3
  • Ghi chú khi chuỗi đường dẫn biểu thị thư mục
  • Nhận tiện ích mở rộng:
    filepath = './dir/subdir/filename.ext'
    
    4
    • Tạo một chuỗi đường dẫn với một tiện ích mở rộng khác
    • Nhận tiện ích mở rộng mà không có dấu chấm [khoảng thời gian]
    • Ví dụ về các trường hợp như
      filepath = './dir/subdir/filename.ext'
      
      5
  • Tạo chuỗi đường dẫn bằng cách kết hợp tên tệp và tên thư mục:
    filepath = './dir/subdir/filename.ext'
    
    6
    • Tạo chuỗi đường dẫn cho một tệp khác trong cùng một thư mục
  • Sử dụng các định dạng hệ điều hành khác nhau
  • Ví dụ cho Windows
    • Backslash và chuỗi thô
    • Ví dụ về việc nhận tên tệp, tên thư mục, tiện ích mở rộng
    • Nhận và tham gia một ký tự ổ đĩa:
      filepath = './dir/subdir/filename.ext'
      
      7

Sử dụng chuỗi đường dẫn sau làm ví dụ.

import os

filepath = './dir/subdir/filename.ext'

Mã mẫu dưới đây đang chạy trên máy Mac. Ví dụ cho Windows được hiển thị ở cuối.

Trong Python 3.4 trở lên, bạn cũng có thể lấy tên tệp, thư mục [thư mục], mở rộng, v.v., với mô -đun Pathlib coi các đường dẫn là đối tượng.

  • Pathlib-Đường dẫn hệ thống tập tin hướng đối tượng-Tài liệu Python 3.9.1RC1

Sự khác biệt về phân tách đường dẫn bằng hệ điều hành

Nhận tên tệp [basename] từ một đường dẫn:

filepath = './dir/subdir/filename.ext'
1

Tên tệp với phần mở rộng

print[os.sep]
# /

print[os.sep is os.path.sep]
# True

Nhận tên tệp [basename] từ một đường dẫn:
filepath = './dir/subdir/filename.ext'
1

Tên tệp với phần mở rộng

Tên tệp với phần mở rộng

Tên tệp mà không cần mở rộng

Lấy tên thư mục [thư mục] từ một đường dẫn:

filepath = './dir/subdir/filename.ext'
2

basename = os.path.basename[filepath]
print[basename]
# filename.ext

print[type[basename]]
# 

Tên tệp mà không cần mở rộng

Lấy tên thư mục [thư mục] từ một đường dẫn:

filepath = './dir/subdir/filename.ext'
2

basename_without_ext = os.path.splitext[os.path.basename[filepath]][0]
print[basename_without_ext]
# filename

Nhận cặp tệp và tên thư mục:

filepath = './dir/subdir/filename.ext'
3

  • Ghi chú khi chuỗi đường dẫn biểu thị thư mục

Nhận tiện ích mở rộng:

filepath = './dir/subdir/filename.ext'
4

Lấy tên thư mục [thư mục] từ một đường dẫn:
filepath = './dir/subdir/filename.ext'
2

Nhận cặp tệp và tên thư mục:

filepath = './dir/subdir/filename.ext'
3

filepath = './dir/subdir/filename.ext'

dirname = os.path.dirname[filepath]
print[dirname]
# ./dir/subdir

print[type[dirname]]
# 

Ghi chú khi chuỗi đường dẫn biểu thị thư mục

/a/b/c/             # nothing, pathname ends with the dir 'c'
c:\windows\         # nothing, pathname ends with the dir 'windows'
c:hello.txt         # matches potential filename 'hello.txt'
~it_s_me/.bashrc    # matches potential filename '.bashrc'
c:\windows\system32 # matches potential filename 'system32', except
                    # that is obviously a dir. os.path.is_dir[]
                    # should be used to tell us for sure
0

Nhận cặp tệp và tên thư mục:
filepath = './dir/subdir/filename.ext'
3

Ghi chú khi chuỗi đường dẫn biểu thị thư mục

Nhận tiện ích mở rộng:

filepath = './dir/subdir/filename.ext'
4

filepath = './dir/subdir/filename.ext'

/a/b/c/             # nothing, pathname ends with the dir 'c'
c:\windows\         # nothing, pathname ends with the dir 'windows'
c:hello.txt         # matches potential filename 'hello.txt'
~it_s_me/.bashrc    # matches potential filename '.bashrc'
c:\windows\system32 # matches potential filename 'system32', except
                    # that is obviously a dir. os.path.is_dir[]
                    # should be used to tell us for sure
2

Tạo một chuỗi đường dẫn với một tiện ích mở rộng khác

  • Nhận tiện ích mở rộng mà không có dấu chấm [khoảng thời gian]

/a/b/c/             # nothing, pathname ends with the dir 'c'
c:\windows\         # nothing, pathname ends with the dir 'windows'
c:hello.txt         # matches potential filename 'hello.txt'
~it_s_me/.bashrc    # matches potential filename '.bashrc'
c:\windows\system32 # matches potential filename 'system32', except
                    # that is obviously a dir. os.path.is_dir[]
                    # should be used to tell us for sure
3

Ví dụ về các trường hợp như

filepath = './dir/subdir/filename.ext'
5

Ghi chú khi chuỗi đường dẫn biểu thị thư mục

Nhận tiện ích mở rộng:

filepath = './dir/subdir/filename.ext'
4

Tạo một chuỗi đường dẫn với một tiện ích mở rộng khác

/a/b/c/             # nothing, pathname ends with the dir 'c'
c:\windows\         # nothing, pathname ends with the dir 'windows'
c:hello.txt         # matches potential filename 'hello.txt'
~it_s_me/.bashrc    # matches potential filename '.bashrc'
c:\windows\system32 # matches potential filename 'system32', except
                    # that is obviously a dir. os.path.is_dir[]
                    # should be used to tell us for sure
4

Nhận tiện ích mở rộng mà không có dấu chấm [khoảng thời gian]

/a/b/c/             # nothing, pathname ends with the dir 'c'
c:\windows\         # nothing, pathname ends with the dir 'windows'
c:hello.txt         # matches potential filename 'hello.txt'
~it_s_me/.bashrc    # matches potential filename '.bashrc'
c:\windows\system32 # matches potential filename 'system32', except
                    # that is obviously a dir. os.path.is_dir[]
                    # should be used to tell us for sure
5

Nhận tiện ích mở rộng:
filepath = './dir/subdir/filename.ext'
4

Sử dụng

filepath = './dir/subdir/filename.ext'
4 để có được phần mở rộng.

filepath = './dir/subdir/filename.ext'
4 chia phần mở rộng và các phần khác và trả lại nó như một tuple. Phần mở rộng chứa dấu chấm
basename = os.path.basename[filepath]
print[basename]
# filename.ext

print[type[basename]]
# 
7.

filepath = './dir/subdir/filename.ext'

/a/b/c/             # nothing, pathname ends with the dir 'c'
c:\windows\         # nothing, pathname ends with the dir 'windows'
c:hello.txt         # matches potential filename 'hello.txt'
~it_s_me/.bashrc    # matches potential filename '.bashrc'
c:\windows\system32 # matches potential filename 'system32', except
                    # that is obviously a dir. os.path.is_dir[]
                    # should be used to tell us for sure
7

Kết nối với toán tử

filepath_tar_gz = './dir/subdir/filename.tar.gz'

print[os.path.splitext[os.path.basename[filepath_tar_gz]][0]]
# filename.tar

print[os.path.basename[filepath_tar_gz].split['.', 1][0]]
# filename
5 trả về chuỗi đường dẫn ban đầu.

  • Chuỗi Concatenate trong Python [+ toán tử, tham gia, v.v.]

/a/b/c/             # nothing, pathname ends with the dir 'c'
c:\windows\         # nothing, pathname ends with the dir 'windows'
c:hello.txt         # matches potential filename 'hello.txt'
~it_s_me/.bashrc    # matches potential filename '.bashrc'
c:\windows\system32 # matches potential filename 'system32', except
                    # that is obviously a dir. os.path.is_dir[]
                    # should be used to tell us for sure
8

Tạo một chuỗi đường dẫn với một tiện ích mở rộng khác

Để tạo một chuỗi đường dẫn chỉ có phần mở rộng được thay đổi từ bản gốc, hãy nối phần tử đầu tiên của tuple được trả về bởi

filepath = './dir/subdir/filename.ext'
4 với bất kỳ tiện ích mở rộng nào.

/a/b/c/             # nothing, pathname ends with the dir 'c'
c:\windows\         # nothing, pathname ends with the dir 'windows'
c:hello.txt         # matches potential filename 'hello.txt'
~it_s_me/.bashrc    # matches potential filename '.bashrc'
c:\windows\system32 # matches potential filename 'system32', except
                    # that is obviously a dir. os.path.is_dir[]
                    # should be used to tell us for sure
9

Nhận tiện ích mở rộng mà không có dấu chấm [khoảng thời gian]

Nếu bạn muốn nhận phần mở rộng mà không có dấu chấm [khoảng thời gian]

basename = os.path.basename[filepath]
print[basename]
# filename.ext

print[type[basename]]
# 
7, hãy chỉ định chuỗi thứ hai và tiếp theo với lát
filepath_tar_gz = './dir/subdir/filename.tar.gz'

print[os.path.splitext[os.path.basename[filepath_tar_gz]][0]]
# filename.tar

print[os.path.basename[filepath_tar_gz].split['.', 1][0]]
# filename
8.

  • Cách cắt một danh sách, chuỗi, tuple trong Python

import os

filepath = './dir/subdir/filename.ext'
0

Ví dụ về các trường hợp như
filepath = './dir/subdir/filename.ext'
5

Như được hiển thị trong ví dụ trên,

filepath = './dir/subdir/filename.ext'
4 chia ở điểm cuối cùng [phải] DOT
basename = os.path.basename[filepath]
print[basename]
# filename.ext

print[type[basename]]
# 
7. Hãy cẩn thận với các phần mở rộng như
filepath = './dir/subdir/filename.ext'
5.

import os

filepath = './dir/subdir/filename.ext'
1

import os

filepath = './dir/subdir/filename.ext'
2

Nếu bạn muốn chia theo dấu chấm đầu tiên [trái] trong tên tệp, hãy sử dụng phương thức

basename = os.path.basename[filepath]
print[basename]
# filename.ext

print[type[basename]]
# 
9 của chuỗi, nhưng nó không hoạt động nếu tên thư mục cũng chứa dot
basename = os.path.basename[filepath]
print[basename]
# filename.ext

print[type[basename]]
# 
7.

import os

filepath = './dir/subdir/filename.ext'
3

Sau khi chia tách với

filepath = './dir/subdir/filename.ext'
3, áp dụng phương pháp
basename = os.path.basename[filepath]
print[basename]
# filename.ext

print[type[basename]]
# 
9 của chuỗi và tham gia với
filepath = './dir/subdir/filename.ext'
6 được mô tả sau.

Chuỗi được trả về bởi

basename = os.path.basename[filepath]
print[basename]
# filename.ext

print[type[basename]]
# 
9 không chứa dấu phân cách, vì vậy hãy cẩn thận nếu bạn muốn nhận tiện ích mở rộng với dấu chấm
basename = os.path.basename[filepath]
print[basename]
# filename.ext

print[type[basename]]
# 
7 như
filepath = './dir/subdir/filename.ext'
4.

import os

filepath = './dir/subdir/filename.ext'
4

Tạo chuỗi đường dẫn bằng cách kết hợp tên tệp và tên thư mục:
filepath = './dir/subdir/filename.ext'
6

Sử dụng

filepath = './dir/subdir/filename.ext'
6 để tham gia tên tệp và thư mục để tạo chuỗi đường dẫn mới.

import os

filepath = './dir/subdir/filename.ext'
5

Tạo chuỗi đường dẫn cho một tệp khác trong cùng một thư mục

Nếu bạn muốn tạo một chuỗi đường dẫn cho một tệp khác trong cùng một thư mục của một tệp, hãy sử dụng

filepath = './dir/subdir/filename.ext'
2 và
filepath = './dir/subdir/filename.ext'
6.

filepath = './dir/subdir/filename.ext'

import os

filepath = './dir/subdir/filename.ext'
7

Sử dụng các định dạng hệ điều hành khác nhau

Nếu bạn muốn thao tác các chuỗi đường dẫn ở định dạng hệ điều hành không phải là hệ điều hành mà Python hiện đang chạy, nhập và sử dụng các mô -đun khác nhau thay vì mô -đun

dirname = os.path.dirname[filepath]
print[dirname]
# ./dir/subdir

print[type[dirname]]
# 
6.

  • UNIX [bao gồm MAC hiện tại]:
    dirname = os.path.dirname[filepath]
    print[dirname]
    # ./dir/subdir
    
    print[type[dirname]]
    # 
    
    7
  • Windows:
    dirname = os.path.dirname[filepath]
    print[dirname]
    # ./dir/subdir
    
    print[type[dirname]]
    # 
    
    8
  • Macintosh 9 và sớm hơn:
    dirname = os.path.dirname[filepath]
    print[dirname]
    # ./dir/subdir
    
    print[type[dirname]]
    # 
    
    9

Vì mỗi mô -đun có cùng giao diện với

filepath = './dir/subdir/filename.ext'
0, bạn có thể thay đổi phần
filepath = './dir/subdir/filename.ext'
0 của mã mẫu cho đến nay thành tên mô -đun của chúng [như
dirname = os.path.dirname[filepath]
print[dirname]
# ./dir/subdir

print[type[dirname]]
# 
8].

Ví dụ cho Windows

Mã mẫu dưới đây đang chạy trên MAC bằng mô -đun

dirname = os.path.dirname[filepath]
print[dirname]
# ./dir/subdir

print[type[dirname]]
# 
8 được đề cập ở trên. Khi chạy trên Windows, bạn có thể thay thế
dirname = os.path.dirname[filepath]
print[dirname]
# ./dir/subdir

print[type[dirname]]
# 
8 bằng
filepath = './dir/subdir/filename.ext'
0.

Backslash và chuỗi thô

Bộ phân cách đường dẫn trong Windows là Backslash

filepath = './dir/subdir/filename.ext'
9.

Để viết dấu gạch chéo ngược trong một chuỗi, bạn cần viết hai dấu gạch chéo ngược để trốn thoát.

/a/b/c/             # nothing, pathname ends with the dir 'c'
c:\windows\         # nothing, pathname ends with the dir 'windows'
c:hello.txt         # matches potential filename 'hello.txt'
~it_s_me/.bashrc    # matches potential filename '.bashrc'
c:\windows\system32 # matches potential filename 'system32', except
                    # that is obviously a dir. os.path.is_dir[]
                    # should be used to tell us for sure
07 đầu ra một dấu gạch chéo ngược.

  • 2. Phân tích từ vựng - Chuỗi và byte theo nghĩa đen - Python 3.9.1RC1 Tài liệu

import os

filepath = './dir/subdir/filename.ext'
8

Chuỗi RAW [

/a/b/c/             # nothing, pathname ends with the dir 'c'
c:\windows\         # nothing, pathname ends with the dir 'windows'
c:hello.txt         # matches potential filename 'hello.txt'
~it_s_me/.bashrc    # matches potential filename '.bashrc'
c:\windows\system32 # matches potential filename 'system32', except
                    # that is obviously a dir. os.path.is_dir[]
                    # should be used to tell us for sure
08] giúp viết đường dẫn Windows dễ dàng hơn vì bạn có thể viết dấu gạch chéo ngược như nó là. Một chuỗi thô và một chuỗi bình thường có giá trị bằng nhau.

import os

filepath = './dir/subdir/filename.ext'
9

Để biết thêm thông tin về chuỗi thô, xem bài viết sau.

  • Dây thô trong Python

Ví dụ về nhận tên tệp, tên thư mục, tiện ích mở rộng

Nó cũng hoạt động trên Windows.

print[os.sep]
# /

print[os.sep is os.path.sep]
# True
0

Nhận và tham gia một ký tự ổ đĩa:
filepath = './dir/subdir/filename.ext'
7

Sử dụng

filepath = './dir/subdir/filename.ext'
7 để lấy ký tự ổ đĩa. Mã mẫu dưới đây sử dụng
/a/b/c/             # nothing, pathname ends with the dir 'c'
c:\windows\         # nothing, pathname ends with the dir 'windows'
c:hello.txt         # matches potential filename 'hello.txt'
~it_s_me/.bashrc    # matches potential filename '.bashrc'
c:\windows\system32 # matches potential filename 'system32', except
                    # that is obviously a dir. os.path.is_dir[]
                    # should be used to tell us for sure
11.

filepath = './dir/subdir/filename.ext'
7 phân chia ký tự ổ đĩa bao gồm Đại tá
/a/b/c/             # nothing, pathname ends with the dir 'c'
c:\windows\         # nothing, pathname ends with the dir 'windows'
c:hello.txt         # matches potential filename 'hello.txt'
~it_s_me/.bashrc    # matches potential filename '.bashrc'
c:\windows\system32 # matches potential filename 'system32', except
                    # that is obviously a dir. os.path.is_dir[]
                    # should be used to tell us for sure
13 và những người khác.

print[os.sep]
# /

print[os.sep is os.path.sep]
# True
1

Nếu bạn chỉ muốn nhận được ký tự ổ đĩa, hãy chọn ký tự đầu tiên.

print[os.sep]
# /

print[os.sep is os.path.sep]
# True
2

Hãy cẩn thận khi tham gia các ký tự ổ đĩa.

Nếu bạn chuyển nó cho

filepath = './dir/subdir/filename.ext'
6 như nó là, nó sẽ không hoạt động.

print[os.sep]
# /

print[os.sep is os.path.sep]
# True
3

Bạn cũng có thể chỉ định

basename = os.path.basename[filepath]
print[basename]
# filename.ext

print[type[basename]]
# 
0 [
/a/b/c/             # nothing, pathname ends with the dir 'c'
c:\windows\         # nothing, pathname ends with the dir 'windows'
c:hello.txt         # matches potential filename 'hello.txt'
~it_s_me/.bashrc    # matches potential filename '.bashrc'
c:\windows\system32 # matches potential filename 'system32', except
                    # that is obviously a dir. os.path.is_dir[]
                    # should be used to tell us for sure
16 trong mã mẫu] trong đối số của
filepath = './dir/subdir/filename.ext'
6 hoặc thêm một dấu tách vào ký tự ổ đĩa.

print[os.sep]
# /

print[os.sep is os.path.sep]
# True
4

Làm cách nào để tách tên tệp và đường dẫn?

Để trích xuất tên tệp từ tệp, chúng tôi sử dụng phương thức của getfileName [] Phương thức của lớp đường dẫn.Phương pháp này được sử dụng để lấy tên tệp và phần mở rộng của chuỗi đường dẫn được chỉ định.Giá trị trả về là null nếu đường dẫn tệp là null.use “GetFileName[]” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null.

Làm cách nào để đọc một tên tệp từ con đường trong Python?

Chương trình Python để lấy tên tệp từ đường dẫn tệp..
Nhập hệ điều hành # Tên tệp với phần mở rộng file_name = os.path.basename ['/root/file.ext'] # Tên tệp không có phần mở rộng in [os.path.splitext [file_name] [0]] Chạy mã ..
Nhập bản in hệ điều hành [Os.Path.SpliteXt [File_Name]] ....
từ Pathlib Nhập đường dẫn PRINT [đường dẫn ['/root/file.ext']. Thân cây].

Làm cách nào để xóa tên tệp khỏi đường dẫn trong Python?

Xóa [] Phương thức trong Python được sử dụng để xóa hoặc xóa đường dẫn tệp. in Python is used to remove or delete a file path.

Làm cách nào để lấy tên tệp mà không có phần mở rộng từ một con đường trong Python?

Nhận tên tệp từ đường dẫn mà không cần mở rộng bằng phương thức RSplit [] Python String RSplit [] trả về danh sách các chuỗi sau khi phá chuỗi đã cho từ phía bên phải bởi bộ phân cách được chỉ định.using rsplit[] Python String rsplit[] method returns a list of strings after breaking the given string from the right side by the specified separator.

Bài Viết Liên Quan

Chủ Đề