Hướng dẫn how do i read a filename from the path in python? - làm cách nào để đọc tên tệp từ đườ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.

Show

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à, /a/b/ là một DIR và c:\windows\) cũng vậy, hãy thay đổi Regex thành:

/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. Đố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
/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
1 hoặ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
2 đó 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.

test
7
/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
6
test
9

Tốt hơn để có kiến ​​thức về:

  • Mô-đun OS Python
  • Mô -đun đường dẫn Python
  • Biểu cảm thường xuyên

Phương pháp 1: Mô-đun OS PythonPython OS-module

Ví dụ1: Nhận tên tệp từ đường dẫn mà không chia phần mở rộng () & nbsp;1: Get the filename from the path without extension split() 

Hàm Python Split Split () chia văn bản đã cho vào một danh sách các chuỗi bằng cách sử dụng dấu phân cách được xác định và trả về một danh sách các chuỗi đã được chia cho dấu phân cách được cung cấp.

Python3

/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
/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

/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
/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
6
/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

/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
/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
VALORANT.exe
0
VALORANT.exe
1
VALORANT.exe
2
VALORANT.exe
3
VALORANT.exe
4

Output:

VALORANT.exe

Ví dụ 2: Lấy tên tệp từ đường dẫn tệp bằng os.path.basenameGet the File Name From the File Path using os.path.basename

Tên cơ sở trong đường dẫn đã cho có thể thu được bằng cách sử dụng hàm python tích hợp os.path.basename (). Đường dẫn hàm.basename () chấp nhận đối số đường dẫn và trả về tên cơ sở của đường dẫn đường dẫn.

Python3

/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
/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

VALORANT.exe
7
/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
6 ________ 29 & nbsp;

test.txt
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
6
test.txt
2

/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
test.txt
4

Output:

test.txt

Ví dụ 3: Lấy tên tệp từ đường dẫn tệp bằng OS.SpliteXtsplitext

Phương thức này sẽ kết thúc với một tệp và nó là một tiện ích mở rộng nhưng nếu chúng ta chỉ cần tên tệp không có phần mở rộng hoặc chỉ các phần mở rộng. Ở đây chức năng Splitext trong mô -đun HĐH đi vào hình ảnh. Phương pháp này sẽ trả về một bộ các chuỗi chứa tên tệp và văn bản và chúng ta có thể truy cập chúng với sự trợ giúp của việc lập chỉ mục.splitext function in the os module comes into the picture. This method will return a tuple of strings containing filename and text and we can access them with the help of indexing.

Example:

Python3

/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
/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

VALORANT.exe
7
/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
6
VALORANT.exe
9

test.txt
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
6
test.txt
2

Ví dụ 3: Lấy tên tệp từ đường dẫn tệp bằng OS.SpliteXt

/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
('test', '.txt')
test.txt
7
('test', '.txt')
test.txt
3
('test', '.txt')
test.txt
9

Phương thức này sẽ kết thúc với một tệp và nó là một tiện ích mở rộng nhưng nếu chúng ta chỉ cần tên tệp không có phần mở rộng hoặc chỉ các phần mở rộng. Ở đây chức năng Splitext trong mô -đun HĐH đi vào hình ảnh. Phương pháp này sẽ trả về một bộ các chuỗi chứa tên tệp và văn bản và chúng ta có thể truy cập chúng với sự trợ giúp của việc lập chỉ mục.

Output:

('test', '.txt')
test.txt

/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 /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 4Get the File Name From the File Path Using Pathlib

VALORANT.exe
7
/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
6
VALORANT.exe
9

Example:

Python3

('test', '.txt')
test.txt
3
/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
6
('test', '.txt')
test.txt
5

VALORANT.exe
7
/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
6
VALORANT.exe
9

/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
Pattern - [\w]+?(?=\.)
9

/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
test
1

Output:

test
test.txt

('test', '.txt') test.txt3 /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 6 ('test', '.txt') test.txt5Get the File Name From the File Path Using Regular expressions

Các

Pattern - [\w]+?(?=\.)

Phương pháp 2: Lấy tên tệp từ đường dẫn tệp bằng cách sử dụng pathlib

  • Gói Python Pathlib cung cấp một số lớp mô tả các đường dẫn hệ thống tệp với ngữ nghĩa phù hợp cho nhiều hệ điều hành. Các mô -đun tiện ích tiêu chuẩn cho Python bao gồm mô -đun này. Mặc dù & nbsp; thân cây là một trong những thuộc tính tiện ích cho phép trích xuất tên tệp từ liên kết mà không cần mở rộng nếu chúng tôi muốn một phần mở rộng với tệp chúng tôi có thể sử dụng thuộc tính tên
  • Pattern - [\w]+?(?=\.)
    1
    Pattern - [\w]+?(?=\.)
    2
    /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
    Pattern - [\w]+?(?=\.)
    4? keyword
  • Phương pháp 3: Lấy tên tệp từ đường dẫn tệp bằng cách sử dụng các biểu thức thông thường

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

Example:

Python3

Chúng ta có thể sử dụng một biểu thức thông thường để phù hợp với tên tệp với mẫu cụ thể.

VALORANT.exe
7
/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
6
VALORANT.exe
9

('test', '.txt')
test.txt
3
/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
6
('test', '.txt')
test.txt
5

Cá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
8/a/b/4

Output:

test

Làm thế nào để bạn đọc một tệp từ một đường dẫn cụ thể trong Python?

Approach:..
Nhập mô -đun ..
Thêm đường dẫn của thư mục ..
Thay đổi thư mục ..
Nhận danh sách một tệp từ một thư mục ..
Lặp lại thông qua danh sách tệp và kiểm tra xem phần mở rộng của tệp có ở hay không. Định dạng TXT hay không ..
Nếu tệp văn bản tồn tại, hãy đọc tệp bằng cách xử lý tệp ..

Làm thế nào để bạn nhập một tên tệp vào python?

inputFileName = input ("Nhập tên của tệp đầu vào:") Biến (Tệp là khóa bị khóa để viết). 1. Open the file and associate the file with a file variable (file is “locked” for writing).

Làm thế nào để tôi duyệt qua con đường trong Python?

Phương pháp 2: Tìm đường dẫn đến tệp đã cho bằng phương thức OS.GetCwd ().Hàm này của mô -đun HĐH Python trả về chuỗi chứa đường dẫn tuyệt đối đến thư mục làm việc hiện tại.os. getcwd() method. This function of the Python OS module returns the string containing the absolute path to the current working directory.

Làm cách nào để nhận 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.Cú pháp: chuỗi tĩnh công khai getFileName (đường dẫn chuỗi);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. Syntax: public static string GetFileName (string path);