Hướng dẫn os python là gì

Trong bài hướng dẫn này về  Module os của Lập trình không khó, chúng ta sẽ tìm hiểu về Module os và các phương thức của nó. Hơn nữa, chúng ta sẽ nghiên cứu cú pháp và ví dụ về Module os trong Ngôn ngữ lập trình Python.

Module là một module tích hợp sẵn với Python, module này cho phép chúng ta thao tác với tệp  và thư mục. Hãy cùng tìm hiểu về những tính năng và phương thức mà module os mang lại. Đầu tiên để sử dụng module os, hãy import module os  bằng lệnh import

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

['DirEntry','F_OK','MutableMapping','O_APPEND','O_BINARY','O_CREAT','O_EXCL',

'O_NOINHERIT','O_RANDOM', 'O_RDONLY','O_RDWR','O_SEQUENTIAL','O_SHORT_LIVED','O_TEMPORARY',

'O_TEXT','O_TRUNC','O_WRONLY','P_DETACH', 'P_NOWAIT','P_NOWAITO','P_OVERLAY','P_WAIT',

'PathLike','R_OK','SEEK_CUR','SEEK_END','SEEK_SET', 'TMP_MAX','W_OK','X_OK','_Environ',

'__all__','__builtins__','__cached__','__doc__','__file__', '__loader__','__name__',

'__package__','__spec__','_execvpe','_exists','_exit','_fspath','_get_exports_list',

'_putenv', '_unsetenv','_wrap_close','abc','abort','access','altsep','chdir','chmod',

'close','closerange', 'cpu_count','curdir','defpath','device_encoding','devnull','dup',

'dup2','environ','error','execl', 'execle','execlp','execlpe','execv','execve','execvp',

'execvpe','extsep','fdopen','fsdecode', 'fsencode','fspath','fstat','fsync','ftruncate',

'get_exec_path','get_handle_inheritable','get_inheritable','get_terminal_size', 'getcwd',

'getcwdb','getenv','getlogin','getpid','getppid','isatty','kill','linesep','link',

'listdir','lseek','lstat','makedirs','mkdir','name','open','pardir','path','pathsep',

'pipe', 'popen','putenv','read','readlink','remove','removedirs','rename','renames',

'replace','rmdir', 'scandir','sep','set_handle_inheritable','set_inheritable','spawnl',

'spawnle','spawnv','spawnve','st', 'startfile','stat','stat_result','statvfs_result',

'strerror','supports_bytes_environ','supports_dir_fd','supports_effective_ids',

'supports_fd', 'supports_follow_symlinks','symlink','sys','system','terminal_size','times',

'times_result','truncate','umask', 'uname_result','unlink','urandom','utime','waitpid',

'walk','write']

Tính ra thì cũng khá nhiều, tuy nhiên về thực tế thì chúng ta không cần nhớ hết tất cả các hàm, phương thức này. Bản thân tôi cũng chỉ thực sự làm việc với một vài hàm trong module os này, và hôm nay tôi sẽ giới thiệu chúng cho các bạn.

import os

print(os.getcwd())

# Tôi đang sử dụng IDLE của Python và file làm việc của tôi được lưu ở F:\Idle python

nênkếtqutrvca tôilàF:\Idle python

#in ra toàn bộ thư muc/tệp đang hiện hành

print(os.listdir())

#in ra tất cả các tệp/thư mục của đường dẫn được truyền vào, ở đây là ổ đĩa D

print(os.listdir("D:\\"))

Phương thức này sẽ duyệt qua hệ thống tệp. Tôi sẽ giải thích về hàm này thông qua ví dụ phía dưới.

import os

for(root,dirs,files)inos.walk('F:\\code',topdown=True):

    print(root)

    print(dirs)

    print(files)

    print('--------------------------------')

Kết quả:

F:\code

['test']

['a.py', 'hihi.txt']

--------------------------------

F:\code\sfdsd

[]

['Tài liệu Văn bản Mới.txt']

--------------------------------

os.walk() duyệt tệp trong cây thư mục bằng cách di chuyển cây từ trên xuống hoặc từ dưới lên. Đối với mỗi thư mục trong cây bắt nguồn từ đầu thư mục (bao gồm cả chính nó), nó mang lại một bộ 3 (dirpath, dirnames, namefile).

  • root: Chỉ: in ra các thư mục từ những gì bạn đã chỉ định.
  • dirs: in ra các thư mục con từ root.
  • files: in ra tất cả các tập tin từ thư mục gốc và thư mục.

Tham số topdown = True bạn có thể bỏ qua hoặc cho nó bằng False để duyệ từ dưới lên

import os

#xem thư mục đang làm việc hiện tại

print(os.getcwd())

os.chdir('F:\\code')

#xem lại sau khi đổi chúng ta đang ở đâu

print(os.getcwd())

Như vậy sau khi sử dụng os.chdir() chúng ta đã từ thư mục ban đầu là F:\Idle python sang F:\code.

import os

path='F:\\code'

#di chuyển đến thư mục đích

os.chdir(path)

print(os.listdir(path))

#tạo một thưu mục mới có tên là testdir

os.mkdir('testdir')

print(os.listdir(path))

['a.py','hihi.txt','sfdsd']

['a.py','hihi.txt','sfdsd','testdir']

Module os cũng cung cấp cho chúng ta phương thức os.rmdir() để thực hiện việc xóa thư mục hiện tại

import os

path='F:\\code'

os.chdir(path)

print(os.listdir(path))

#Xóa thư mục có tên testdir mới tạo ở trên

os.rmdir('testdir')

print(os.listdir(path))

['a.py','hihi.txt','sfdsd','testdir']

['a.py','hihi.txt','sfdsd']

Trong bài viết này, chúng tôi đã tìm hiểu ngắn gọn về các phương thưc phổ biến khác nhau của module os . Chúng tôi cũng đã thấy một vài ví dụ ngắn gọn cho mỗi trường hợp. Điều quan trọng là phải hiểu rằng module os còn cung cấp nhiều phương thức khác hưu dụng hơn nữa.