유용하지만 거의 사용되지 않는 Python의 OS 함수

Patricia Arquette
풀어 주다: 2024-11-15 11:01:03
원래의
949명이 탐색했습니다.

Useful but Rarely Used OS Functions in Python

Python の os モジュールによって提供される関数をプロジェクト内で何度か使用したことがあるはずです。これらは、ファイルの作成、ディレクトリの移動、現在のディレクトリの情報の取得、パス操作の実行などに使用できます。

この記事では、os モジュールの他の関数と同じくらい便利だが、めったに使用されない関数について説明します。

os.path.commonpath()

共通のディレクトリ構造を共有する複数のファイルを操作する場合、最長の共有パスを見つけたい場合があります。 os.path.commonpath() はまさにそれを行います。これは、ファイルを整理したり、環境間で異なるパスを処理したりするときに役立ちます。

これが例です:

import os

paths = ['/user/data/project1/file1.txt', '/user/data/project2/file2.txt']
common_path = os.path.commonpath(paths)
print("Common Path:", common_path)
로그인 후 복사

このコードは、これら 2 つのパスが共有する共通のパスを提供します。

Common Path: /user/data
로그인 후 복사

os.path.commonpath() がパス名のリストを取得することがわかりますが、パス名を手動で書き留めるのは現実的ではない可能性があります。

その場合、すべてのディレクトリ、サブディレクトリ、ファイル名を繰り返し処理して、共通のパスを探すのが最善です。

import os

def get_file_paths(directory, file_extension=None):
    # Collect all file paths in the directory (and subdirectories, if any)
    file_paths = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file_extension is None or file.endswith(file_extension):
                file_paths.append(os.path.join(root, file))
    return file_paths


# Specify the root directory to start from
directory_path = 'D:/SACHIN/Pycharm/Flask-Tutorial'

# If you want to filter by file extension
file_paths = get_file_paths(directory_path, file_extension='.html')

# Find the common path among all files
if file_paths:
    common_path = os.path.commonpath(file_paths)
    print("Common Path:", common_path)
else:
    print("No files found in the specified directory.")
로그인 후 복사

この例では、関数 get_file_paths() はディレクトリを上から下まで走査し、file_paths リストで見つかったすべてのパスを追加します。特定のファイルを探したい場合、この関数はオプションでファイル拡張子を受け取ります。

これで、任意のディレクトリの共通パスを簡単に見つけることができます。

Common Path: D:\SACHIN\Pycharm\Flask-Tutorial\templates
로그인 후 복사

os.scandir()

ディレクトリの内容を取得するために os.listdir() を使用している場合は、代わりに os.scandir() の使用を検討してください。高速なだけでなく、ファイル タイプ、アクセス許可、エントリがファイルであるかディレクトリであるかなどの有用な情報を提供する DirEntry オブジェクトも返します。

これが例です:

import os

with os.scandir('D:/SACHIN/Pycharm/osfunctions') as entries:
    for entry in entries:
        print(f"{entry.name} : \n"
              f">>>> Is File: {entry.is_file()} \n"
              f">>>> Is Directory: {entry.is_dir()}")
로그인 후 복사

この例では、os.scandir() を使用してディレクトリを渡し、このディレクトリを反復処理して情報を出力しました。

.idea : 
>>>> Is File: False 
>>>> Is Directory: True
main.py : 
>>>> Is File: True 
>>>> Is Directory: False
sample.py : 
>>>> Is File: True 
>>>> Is Directory: False
로그인 후 복사

os.path.splitext()

ファイルを操作していて、その拡張子を確認する必要があるとします。os.path.splitext() 関数を使用すると役立ちます。ファイル パスをルートと拡張子に分割するため、ファイルの種類を判断するのに役立ちます。

import os

filename = 'report.csv'
root, ext = os.path.splitext(filename)
print(f"Root: {root} \n"
      f"Extension: {ext}")
로그인 후 복사

出力

Root: report 
Extension: .csv
로그인 후 복사

パスが奇妙になる可能性があるいくつかのケースと、そのときの os.path.splitext() の動作を見てください。

import os

filename = ['.report', 'report', 'report.case.txt', 'report.csv.zip']
for idx, paths in enumerate(filename):
    root, ext = os.path.splitext(paths)
    print(f"{idx} - {paths}\n"
          f"Root: {root} | Extension: {ext}")
로그인 후 복사

出力

0 - .report
Root: .report | Extension: 
1 - report
Root: report | Extension: 
2 - report.case.txt
Root: report.case | Extension: .txt
3 - report.csv.zip
Root: report.csv | Extension: .zip
로그인 후 복사

os.makedirs()

ディレクトリを作成できる、頻繁に使用される関数がすでにあります。しかし、ネストされたディレクトリを作成する場合はどうでしょうか?

Creating nested directories can be a hassle with os.mkdir() since it only makes one directory at a time. os.makedirs() allows you to create multiple nested directories in one go, and the exist_ok=True argument makes sure it doesn’t throw an error if the directory already exists.

import os

os.makedirs('project/data/files', exist_ok=True)
print("Nested directories created!")
로그인 후 복사

When we run this program, it will create specified directories and sub-directories.

Nested directories created!
로그인 후 복사

If we run the above program again, it won’t throw an error due to exist_ok=True.

os.replace()

Similar to os.rename(), os.replace() moves a file to a new location, but it safely overwrites any existing file at the destination. This is helpful for tasks where you’re updating or backing up files and want to ensure that old files are safely replaced.

import os

os.replace(src='main.py', dst='new_main.py')
print("File replaced successfully!")
로그인 후 복사

In this code, main.py file will be renamed to new_main.py just as os.rename() function but this operation is like take it all or nothing. It means the file replacement happens in a single, indivisible step, so either the entire operation succeeds or nothing changes at all.

File replaced successfully!
로그인 후 복사

os.urandom()

For cryptographic purposes, you need a secure source of random data. os.urandom() generates random bytes suitable for things like generating random IDs, tokens, or passwords. It’s more secure than the random module for sensitive data.

os.urandom() uses randomness generated by the operating system you are using from various resources to make bytes (data) unpredictable.

In Windows, it uses BCryptGenRandom() to generate random bytes.

import os

secure_token = os.urandom(16)  # 16 bytes of random data
print("Secure Token:", secure_token)
#Making it human-readable
print("Secure Token:", secure_token.hex())
로그인 후 복사

Output

Secure Token: b'\x84\xd6\x1c\x1bKB\x7f\xcd\xf6\xb7\xc4D\x92z\xe3{'
Secure Token: 84d61c1b4b427fcdf6b7c444927ae37b
로그인 후 복사

os.path.samefile()

The os.path.samefile() function in Python is used to check if two paths refer to the same file or directory on the filesystem. It’s particularly helpful in scenarios where multiple paths might point to the same physical file, such as when dealing with symbolic links, hard links, or different absolute and relative paths to the same location.

import os

is_same = os.path.samefile('/path/to/file1.txt', '/different/path/to/symlink_file1.txt')
print("Are they the same file?", is_same)
로그인 후 복사

os.path.samefile() is designed to return True only if both paths reference the same file on disk, such as a file that’s hard-linked or symlinked to the same data on the filesystem.

os.path.relpath()

os.path.relpath() is a computation function that computes the relative path between two paths. This is particularly useful when building file paths dynamically or working with relative imports.

Consider the following example:

import os

# Target file path
target_path = "D:/SACHIN/Pycharm/osfunctions/project/engine/log.py"
# Starting point
start_path = "D:/SACHIN/Pycharm/osfunctions/project/interface/character/specific.py"

relative_path = os.path.relpath(target_path, start=start_path)
print(relative_path)
로그인 후 복사

In this example, we have target_path which contains a path where we have to navigate and start_path contains a path from where we have to start calculating the relative path to target_path.

When we run this, we get the following output.

..\..\..\engine\log.py
로그인 후 복사

This means we have to go up three directories and then down to engine/log.py.

os.fsync()

When we perform a file writing (file.write()) operation, the data isn’t saved to disk instantly instead the data is saved into the system’s buffer and if something unexpected happens before writing the data to the disk, the data gets lost.

os.fsync() forces the data to be written, ensuring data integrity. It’s especially useful in logging or when writing critical data that must not be lost.

import os

with open('data.txt', 'w') as f:
    f.write("gibberish!")
    os.fsync(f.fileno())  # Ensures data is written to disk
로그인 후 복사

os.fsync(f.fileno()) is called to make sure the data is immediately written to the disk and not left in the buffer.

os.fsync() takes file descriptor that’s why we passed f.fileno() which is a unique integer assigned by the system to the file on which we are operating.

os.get_terminal_size()

If you’re creating CLI tools, formatting the output to fit the terminal width can make the output cleaner. os.get_terminal_size() gives you the current terminal width and height, making it easy to dynamically format content.

import os

size = os.get_terminal_size()
print(f"Terminal Width: {size.columns}, Terminal Height: {size.lines}")
로그인 후 복사

When we run this code in the terminal, we get the size of the terminal on which we are running this script.

PS > py sample.py
Terminal Width: 158, Terminal Height: 12
로그인 후 복사

Note: You may get an error when directly running the script on IDE where the program doesn’t have access to the terminal.


?Other articles you might be interested in if you liked this one

✅Streaming videos on the frontend in FastAPI.

✅How to fix circular imports in Python.

✅Template inheritance in Flask.

✅How to use type hints in Python?

✅How to find and delete mismatched columns from datasets in pandas?

✅How does the learning rate affect the ML and DL models?


That’s all for now.

Keep Coding✌✌.

위 내용은 유용하지만 거의 사용되지 않는 Python의 OS 함수의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿