Hướng dẫn how to get current file name in python - cách lấy tên tệp hiện tại trong python

Tất cả những câu trả lời đó là tuyệt vời, nhưng có một số vấn đề bạn có thể không thấy ngay từ cái nhìn đầu tiên.

Hãy xác định những gì chúng tôi muốn - chúng tôi muốn tên của tập lệnh được thực thi, không phải tên của mô -đun hiện tại - vì vậy

import os

print('getcwd:      ', os.getcwd())
print('__file__:    ', __file__)
9 sẽ chỉ hoạt động nếu nó được sử dụng trong tập lệnh được thực thi, không phải trong mô -đun nhập.
python3 data/src/file_path.py
# getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
# __file__:     data/src/file_path.py
0 cũng đáng nghi ngờ - điều gì sẽ xảy ra nếu chương trình của bạn được gọi bởi pytest thì sao? Hay người chạy Pydoc? Hoặc nếu nó được gọi bởi UWSGI?

Và - có một phương pháp thứ ba để lấy tên tập lệnh, tôi không thấy trong các câu trả lời - bạn có thể kiểm tra ngăn xếp.

Một vấn đề khác là, bạn (hoặc một số chương trình khác) có thể làm xáo trộn xung quanh với

python3 data/src/file_path.py
# getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
# __file__:     data/src/file_path.py
0 và
python3 data/src/file_path.py
# getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
# __file__:     data/src/file_path.py
2 - nó có thể có mặt, nó có thể không. Nó có thể hợp lệ, hoặc không. Ít nhất bạn có thể kiểm tra xem tập lệnh (kết quả mong muốn) có tồn tại không!

Thư viện lib_programname thực hiện chính xác điều đó:

  • Kiểm tra xem
    python3 data/src/file_path.py
    # getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
    # __file__:     data/src/file_path.py
    
    3 có mặt không
  • Kiểm tra xem
    python3 data/src/file_path.py
    # getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
    # __file__:     data/src/file_path.py
    
    2 có mặt không
  • Có cho
    python3 data/src/file_path.py
    # getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
    # __file__:     data/src/file_path.py
    
    2 một kết quả hợp lệ (tập lệnh đó có tồn tại không?)
  • Nếu không: kiểm tra sys.argv:
  • Có pytest, docrunner, vv trong sys.argv? -> Nếu có, hãy bỏ qua điều đó
  • Chúng ta có thể nhận được một kết quả hợp lệ ở đây không?
  • Nếu không: kiểm tra ngăn xếp và nhận kết quả từ đó có thể
  • Nếu cả ngăn xếp không cho kết quả hợp lệ, thì hãy ném một ngoại lệ.

Bằng cách đó, giải pháp của tôi đang hoạt động cho đến nay với

python3 data/src/file_path.py
# getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
# __file__:     data/src/file_path.py
6,
python3 data/src/file_path.py
# getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
# __file__:     data/src/file_path.py
7,
python3 data/src/file_path.py
# getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
# __file__:     data/src/file_path.py
8,
python3 data/src/file_path.py
# getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
# __file__:     data/src/file_path.py
9,
pwd
# /Users/mbp/Documents/my-project/python-snippets/notebook

python3 /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
# getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
# __file__:     /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
0,
pwd
# /Users/mbp/Documents/my-project/python-snippets/notebook

python3 /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
# getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
# __file__:     /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
1,
pwd
# /Users/mbp/Documents/my-project/python-snippets/notebook

python3 /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
# getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
# __file__:     /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
2

Ngoài ra còn có một bài viết trên blog hay về vấn đề đó từ Dough Hellman, "Xác định tên của một quá trình từ Python"

BTW, nó sẽ thay đổi một lần nữa trong Python 3.9: Thuộc tính tệp của mô -đun chính trở thành một đường dẫn tuyệt đối, thay vì một đường dẫn tương đối. Các đường dẫn này hiện vẫn còn hiệu lực sau khi thư mục hiện tại được thay đổi bởi os.chdir ()file attribute of the main module became an absolute path, rather than a relative path. These paths now remain valid after the current directory is changed by os.chdir()

Vì vậy, tôi muốn chăm sóc một mô -đun nhỏ, thay vì lướt qua cơ sở mã của mình nếu nó nên được thay đổi một số ...


Tuyên bố miễn trừ trách nhiệm: Tôi là tác giả của Thư viện Lib_ProgramName.

Trong Python, bạn có thể nhận được đường dẫn (vị trí) của tệp hiện tại, tức là, hiện đang chạy tệp tập lệnh (

pwd
# /Users/mbp/Documents/my-project/python-snippets/notebook

python3 /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
# getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
# __file__:     /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
3) với
import os

print('getcwd:      ', os.getcwd())
print('__file__:    ', __file__)
9.
import os

print('getcwd:      ', os.getcwd())
print('__file__:    ', __file__)
9 rất hữu ích cho việc đọc các tệp khác dựa trên vị trí của tệp hiện tại.

Trong Python 3.8 và trước đó,

import os

print('getcwd:      ', os.getcwd())
print('__file__:    ', __file__)
9 trả về đường dẫn được chỉ định khi thực thi lệnh
pwd
# /Users/mbp/Documents/my-project/python-snippets/notebook

python3 /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
# getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
# __file__:     /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
7 (hoặc
pwd
# /Users/mbp/Documents/my-project/python-snippets/notebook

python3 /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
# getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
# __file__:     /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
8). Nếu bạn chỉ định một đường dẫn tương đối, một đường dẫn tương đối sẽ được trả về. Nếu bạn chỉ định một đường dẫn tuyệt đối, một đường dẫn tuyệt đối sẽ được trả về.

Trong Python 3.9 trở lên,

import os

print('getcwd:      ', os.getcwd())
print('__file__:    ', __file__)
9 luôn trả về một đường dẫn tuyệt đối, bất kể đường dẫn được chỉ định với lệnh
pwd
# /Users/mbp/Documents/my-project/python-snippets/notebook

python3 /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
# getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
# __file__:     /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
7 là tương đối hay tuyệt đối.

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

  • print('basename:    ', os.path.basename(__file__))
    print('dirname:     ', os.path.dirname(__file__))
    
    1 và
    import os
    
    print('getcwd:      ', os.getcwd())
    print('__file__:    ', __file__)
    
    9
  • Lấy tên tệp và thư mục của tệp tập lệnh hiện tại
  • Nhận đường dẫn tuyệt đối của tệp tập lệnh hiện tại
  • Đọc các tệp khác dựa trên vị trí của tệp tập lệnh hiện tại
  • Thay đổi thư mục hiện tại thành thư mục của tệp tập lệnh hiện tại
  • Đọc cùng một tệp bất kể thư mục làm việc hiện tại

Xem bài viết sau đây về cách lấy và thay đổi thư mục làm việc hiện tại.

  • Nhận và thay đổi thư mục làm việc hiện tại trong Python

Lưu ý rằng

import os

print('getcwd:      ', os.getcwd())
print('__file__:    ', __file__)
9 không thể được sử dụng trong Notebook Jupyter (
print('basename:    ', os.path.basename(__file__))
print('dirname:     ', os.path.dirname(__file__))
4). Bất kể thư mục nơi bắt đầu Notebook Jupyter, thư mục hiện tại là nơi
print('basename:    ', os.path.basename(__file__))
print('dirname:     ', os.path.dirname(__file__))
4 được đặt. Có thể thay đổi thư mục hiện tại bằng cách sử dụng
print('basename:    ', os.path.basename(__file__))
print('dirname:     ', os.path.dirname(__file__))
6 trong mã.

Giả sử bạn làm việc trong thư mục sau. Trên Windows, bạn có thể kiểm tra thư mục hiện tại bằng lệnh

print('basename:    ', os.path.basename(__file__))
print('dirname:     ', os.path.dirname(__file__))
9 thay vì
# basename:     file_path.py
# dirname:      data/src
0.

pwd
# /Users/mbp/Documents/my-project/python-snippets/notebook

Tạo một tệp tập lệnh Python (

# basename:     file_path.py
# dirname:      data/src
1) với mã sau trong thư mục thấp hơn (
# basename:     file_path.py
# dirname:      data/src
2).

import os

print('getcwd:      ', os.getcwd())
print('__file__:    ', __file__)

Chạy nó với lệnh

pwd
# /Users/mbp/Documents/my-project/python-snippets/notebook

python3 /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
# getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
# __file__:     /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
7 (hoặc
pwd
# /Users/mbp/Documents/my-project/python-snippets/notebook

python3 /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
# getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
# __file__:     /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
8).

python3 data/src/file_path.py
# getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
# __file__:     data/src/file_path.py

Bạn có thể nhận đường dẫn tuyệt đối của thư mục làm việc hiện tại với

print('basename:    ', os.path.basename(__file__))
print('dirname:     ', os.path.dirname(__file__))
1 và đường dẫn được chỉ định với lệnh
pwd
# /Users/mbp/Documents/my-project/python-snippets/notebook

python3 /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
# getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
# __file__:     /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
8 với
import os

print('getcwd:      ', os.getcwd())
print('__file__:    ', __file__)
9.

Trong Python 3.8 và trước đó, đường dẫn được chỉ định bởi lệnh

pwd
# /Users/mbp/Documents/my-project/python-snippets/notebook

python3 /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
# getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
# __file__:     /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
7 (hoặc
pwd
# /Users/mbp/Documents/my-project/python-snippets/notebook

python3 /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
# getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
# __file__:     /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
8) được lưu trữ trong
import os

print('getcwd:      ', os.getcwd())
print('__file__:    ', __file__)
9. Trong ví dụ trên, một đường dẫn tương đối được chỉ định, do đó, một đường dẫn tương đối được trả về, nhưng nếu một đường dẫn tuyệt đối được chỉ định, một đường dẫn tuyệt đối được trả về.

pwd
# /Users/mbp/Documents/my-project/python-snippets/notebook

python3 /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
# getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
# __file__:     /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py

Trong Python 3.9 trở lên,

import os

print('getcwd:      ', os.getcwd())
print('__file__:    ', __file__)
9 luôn lưu trữ một đường dẫn tuyệt đối, bất kể đường dẫn được chỉ định với lệnh
pwd
# /Users/mbp/Documents/my-project/python-snippets/notebook

python3 /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
# getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
# __file__:     /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
7 là tương đối hay tuyệt đối.

Trong các ví dụ sau, thêm mã vào cùng một tệp tập lệnh (

# basename:     file_path.py
# dirname:      data/src
1) và thực thi từ cùng một thư mục với ví dụ trên trong Python3.7.

Lưu ý rằng nếu

import os

print('getcwd:      ', os.getcwd())
print('__file__:    ', __file__)
9 là một đường dẫn tuyệt đối (khi Python 3.9 trở lên hoặc khi chỉ định đường dẫn tuyệt đối trong Python 3.8 hoặc sớm hơn), bạn có thể sử dụng cùng một mã như được mô tả dưới đây để đọc các tệp khác dựa trên vị trí của tệp tập lệnh hiện tại . Kết quả thực hiện bằng cách chỉ định đường dẫn tuyệt đối trong Python3.7 được hiển thị ở cuối.

Lấy tên tệp và thư mục của tệp tập lệnh hiện tại

Nhận đường dẫn tuyệt đối của tệp tập lệnh hiện tại

print('basename:    ', os.path.basename(__file__))
print('dirname:     ', os.path.dirname(__file__))

Đọc các tệp khác dựa trên vị trí của tệp tập lệnh hiện tại

# basename:     file_path.py
# dirname:      data/src

Thay đổi thư mục hiện tại thành thư mục của tệp tập lệnh hiện tại

Đọc cùng một tệp bất kể thư mục làm việc hiện tại

  • Xem bài viết sau đây về cách lấy và thay đổi thư mục làm việc hiện tại.

Nhận đường dẫn tuyệt đối của tệp tập lệnh hiện tại

Đọc các tệp khác dựa trên vị trí của tệp tập lệnh hiện tại

print('abspath:     ', os.path.abspath(__file__))
print('abs dirname: ', os.path.dirname(os.path.abspath(__file__)))

Đọc các tệp khác dựa trên vị trí của tệp tập lệnh hiện tại

# abspath:      /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
# abs dirname:  /Users/mbp/Documents/my-project/python-snippets/notebook/data/src

Thay đổi thư mục hiện tại thành thư mục của tệp tập lệnh hiện tại

Đọc các tệp khác dựa trên vị trí của tệp tập lệnh hiện tại

Thay đổi thư mục hiện tại thành thư mục của tệp tập lệnh hiện tại

Đọc cùng một tệp bất kể thư mục làm việc hiện tại

print('[set target path 1]')
target_path_1 = os.path.join(os.path.dirname(__file__), 'target_1.txt')

print('target_path_1: ', target_path_1)

print('read target file:')
with open(target_path_1) as f:
    print(f.read())

Đọc các tệp khác dựa trên vị trí của tệp tập lệnh hiện tại

# [set target path 1]
# target_path_1:  data/src/target_1.txt
# read target file:
# !! This is "target_1.txt" !!

Thay đổi thư mục hiện tại thành thư mục của tệp tập lệnh hiện tại

  • Đọc cùng một tệp bất kể thư mục làm việc hiện tại

import os

print('getcwd:      ', os.getcwd())
print('__file__:    ', __file__)
0

Đọc các tệp khác dựa trên vị trí của tệp tập lệnh hiện tại

import os

print('getcwd:      ', os.getcwd())
print('__file__:    ', __file__)
1

Thay đổi thư mục hiện tại thành thư mục của tệp tập lệnh hiện tại

Đọc cùng một tệp bất kể thư mục làm việc hiện tại

  • Nhận và thay đổi thư mục làm việc hiện tại trong Python

Lưu ý rằng

import os

print('getcwd:      ', os.getcwd())
print('__file__:    ', __file__)
9 không thể được sử dụng trong Notebook Jupyter (
print('basename:    ', os.path.basename(__file__))
print('dirname:     ', os.path.dirname(__file__))
4). Bất kể thư mục nơi bắt đầu Notebook Jupyter, thư mục hiện tại là nơi
print('basename:    ', os.path.basename(__file__))
print('dirname:     ', os.path.dirname(__file__))
4 được đặt. Có thể thay đổi thư mục hiện tại bằng cách sử dụng
print('basename:    ', os.path.basename(__file__))
print('dirname:     ', os.path.dirname(__file__))
6 trong mã.

import os

print('getcwd:      ', os.getcwd())
print('__file__:    ', __file__)
2

Đọc các tệp khác dựa trên vị trí của tệp tập lệnh hiện tại

import os

print('getcwd:      ', os.getcwd())
print('__file__:    ', __file__)
3

Thay đổi thư mục hiện tại thành thư mục của tệp tập lệnh hiện tại

import os

print('getcwd:      ', os.getcwd())
print('__file__:    ', __file__)
4

Đọc các tệp khác dựa trên vị trí của tệp tập lệnh hiện tại

import os

print('getcwd:      ', os.getcwd())
print('__file__:    ', __file__)
5

Đọc cùng một tệp bất kể thư mục làm việc hiện tại

Xem bài viết sau đây về cách lấy và thay đổi thư mục làm việc hiện tại.

Nhận và thay đổi thư mục làm việc hiện tại trong Python

  • Lưu ý rằng
    import os
    
    print('getcwd:      ', os.getcwd())
    print('__file__:    ', __file__)
    
    9 không thể được sử dụng trong Notebook Jupyter (
    print('basename:    ', os.path.basename(__file__))
    print('dirname:     ', os.path.dirname(__file__))
    
    4). Bất kể thư mục nơi bắt đầu Notebook Jupyter, thư mục hiện tại là nơi
    print('basename:    ', os.path.basename(__file__))
    print('dirname:     ', os.path.dirname(__file__))
    
    4 được đặt. Có thể thay đổi thư mục hiện tại bằng cách sử dụng
    print('basename:    ', os.path.basename(__file__))
    print('dirname:     ', os.path.dirname(__file__))
    
    6 trong mã.
  • Thay đổi thư mục làm việc hiện tại thành thư mục
    import os
    
    print('getcwd:      ', os.getcwd())
    print('__file__:    ', __file__)
    
    9.

Việc thay đổi thư mục hiện tại sẽ dễ dàng hơn, nhưng tất nhiên, nếu bạn đọc hoặc ghi tệp sau đó, bạn cần xem xét rằng thư mục hiện tại đã được thay đổi.

Kết quả của các ví dụ cho đến nay là như sau.

import os

print('getcwd:      ', os.getcwd())
print('__file__:    ', __file__)
6

Kết quả để chỉ định đường dẫn tuyệt đối với lệnh

pwd
# /Users/mbp/Documents/my-project/python-snippets/notebook

python3 /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
# getcwd:       /Users/mbp/Documents/my-project/python-snippets/notebook
# __file__:     /Users/mbp/Documents/my-project/python-snippets/notebook/data/src/file_path.py
8 như sau. Bạn có thể đọc cùng một tệp.

import os

print('getcwd:      ', os.getcwd())
print('__file__:    ', __file__)
7

Thay đổi thư mục hiện tại trong thiết bị đầu cuối và thực thi cùng một tệp tập lệnh. Bạn có thể thấy rằng cùng một tệp được đọc từ các vị trí khác nhau.

import os

print('getcwd:      ', os.getcwd())
print('__file__:    ', __file__)
8

Làm cách nào để có được tệp hiện tại trong Python?

Để có được thư mục làm việc hiện tại trong Python, hãy sử dụ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.use the 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 để tìm một tên tệp trong Python?

Python có thể tìm kiếm tên tệp trong một đường dẫn được chỉ định của HĐH.Điều này có thể được thực hiện bằng cách sử dụng HĐH mô -đun với các chức năng đi bộ ().Điều này sẽ lấy một đường dẫn cụ thể làm đầu vào và tạo ra 3-tuple liên quan đến dirpath, dirnames và tên tệp.using the module os with the walk() functions. This will take a specific path as input and generate a 3-tuple involving dirpath, dirnames, and filenames.

Làm cách nào để có được tên tập lệnh hiện tại?

Vì chúng tôi đang sử dụng PHP, chúng tôi có thể dễ dàng lấy tên tệp hoặc tên thư mục hiện tại của trang hiện tại bằng cách sử dụng $ _server ['Script_name'].Sử dụng $ _Server ['Script_name']: $ _Server là một mảng thông tin được lưu trữ như tiêu đề, đường dẫn và vị trí tập lệnh.Các mục này được tạo bởi máy chủ web.$_SERVER['SCRIPT_NAME']. Using $_SERVER['SCRIPT_NAME']: $_SERVER is an array of stored information such as headers, paths, and script locations. These entries are created by the webserver.

__ Tệp __ Python là gì?

__file__ là một biến có chứa đường dẫn đến mô -đun hiện đang được nhập.Python tạo ra một biến __file__ cho chính nó khi nó sắp nhập một mô -đun.a variable that contains the path to the module that is currently being imported. Python creates a __file__ variable for itself when it is about to import a module.