Hướng dẫn open file using absolute path python - mở tệp bằng python đường dẫn tuyệt đối

Nói rằng bạn đang ở trên

>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
4 và muốn gọi tệp
>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
5 sau đó mở tệp
>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
6:

Show
main_folder
│
└───first_folder      
│   │   first_file.py
│   │
|   └───second_folder
│       │ readme.txt             
│
└─── ...

Python cung cấp cho chúng tôi một thuộc tính gọi là

>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
7 trả về đường dẫn tuyệt đối cho tệp. Ví dụ: nói rằng nội dung của
>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
5 chỉ là một dòng in đường dẫn này:
>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
9.

Bây giờ, nếu chúng ta gọi

>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
5 từ
>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
4, chúng ta sẽ nhận được kết quả tương tự rằng nếu chúng ta gọi nó từ
>>> myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
>>> for filename in myFiles:
        print(os.path.join('C:\\Users\\asweigart', filename))
C:\Users\asweigart\accounts.txt
C:\Users\asweigart\details.csv
C:\Users\asweigart\invite.docx
2 (lưu ý rằng, trong Windows, kết quả sẽ khác một chút):

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"

Và nếu chúng tôi muốn có được thư mục của

>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
5, chúng tôi sẽ nhập thư viện
>>> myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
>>> for filename in myFiles:
        print(os.path.join('C:\\Users\\asweigart', filename))
C:\Users\asweigart\accounts.txt
C:\Users\asweigart\details.csv
C:\Users\asweigart\invite.docx
4 và chúng tôi sử dụng phương thức
>>> myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
>>> for filename in myFiles:
        print(os.path.join('C:\\Users\\asweigart', filename))
C:\Users\asweigart\accounts.txt
C:\Users\asweigart\details.csv
C:\Users\asweigart\invite.docx
5.

Cuối cùng, chúng tôi chỉ kết hợp thư mục này với tài liệu chúng tôi muốn truy cập từ nó (

>>> myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
>>> for filename in myFiles:
        print(os.path.join('C:\\Users\\asweigart', filename))
C:\Users\asweigart\accounts.txt
C:\Users\asweigart\details.csv
C:\Users\asweigart\invite.docx
6) và tên của tệp (
>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
6).

Đơn giản hóa, mã kết quả là:

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')

Và giá trị của readme_path:

"/Users/<username>/Documents/github/main_folder/first_folder/second_folder/readme.txt"

Bằng cách này, bạn cũng sẽ không gặp bất kỳ vấn đề nào liên quan đến trình gỡ lỗi mã Visual Studio với đường dẫn và bạn sẽ có thể gọi

>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
5 từ bất cứ nơi nào bạn muốn 🥳

Đọc và ghi tệp

Các biến là một cách tốt để lưu trữ dữ liệu trong khi chương trình của bạn đang chạy, nhưng nếu bạn muốn dữ liệu của mình tồn tại ngay cả sau khi chương trình của bạn kết thúc, bạn cần lưu nó vào một tệp. Bạn có thể nghĩ về một nội dung tệp tệp dưới dạng một giá trị chuỗi duy nhất, có khả năng kích thước gigabyte. Trong chương này, bạn sẽ tìm hiểu cách sử dụng Python để tạo, đọc và lưu các tệp trên ổ cứng.

Tệp và đường dẫn tệp

Một tệp có hai thuộc tính chính: tên tệp (thường được viết là một từ) và một đường dẫn. Đường dẫn chỉ định vị trí của một tệp trên máy tính. Ví dụ: có một tệp trên máy tính xách tay Windows 7 của tôi với FileName Project.docx trong đường dẫn C: \ Users \ Asweigart \ Documents. Phần của tên tệp sau khoảng thời gian cuối cùng được gọi là tiện ích mở rộng tệp và cho bạn biết một loại tệp. Project.docx là một tài liệu từ và người dùng, Asweigart và các tài liệu đều đề cập đến các thư mục (còn được gọi là thư mục). Các thư mục có thể chứa các tập tin và các thư mục khác. Ví dụ: Project.docx nằm trong thư mục tài liệu, nằm trong thư mục Asweigart, nằm trong thư mục người dùng. Hình & NBSP; 8-1 cho thấy tổ chức thư mục này.filename (usually written as one word) and a path. The path specifies the location of a file on the computer. For example, there is a file on my Windows 7 laptop with the filename project.docx in the path C:\Users\asweigart\Documents. The part of the filename after the last period is called the file’s extension and tells you a file’s type. project.docx is a Word document, and Users, asweigart, and Documents all refer to folders (also called directories). Folders can contain files and other folders. For example, project.docx is in the Documents folder, which is inside the asweigart folder, which is inside the Users folder. Figure 8-1 shows this folder organization.

Hướng dẫn open file using absolute path python - mở tệp bằng python đường dẫn tuyệt đối

Hình & nbsp; 8-1. & Nbsp; một tệp trong một phân cấp các thư mục

Phần C: \ của đường dẫn là thư mục gốc, chứa tất cả các thư mục khác. Trên Windows, thư mục gốc được đặt tên là C: \ và còn được gọi là ổ C:. Trên OS X và Linux, thư mục gốc là /. Trong cuốn sách này, tôi sẽ sử dụng thư mục gốc kiểu Windows, C: \. Nếu bạn đang nhập các ví dụ shell tương tác trên OS X hoặc Linux, hãy nhập

>>> myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
>>> for filename in myFiles:
        print(os.path.join('C:\\Users\\asweigart', filename))
C:\Users\asweigart\accounts.txt
C:\Users\asweigart\details.csv
C:\Users\asweigart\invite.docx
9 thay thế.C:\ part of the path is the root folder, which contains all other folders. On Windows, the root folder is named C:\ and is also called the C: drive. On OS X and Linux, the root folder is /. In this book, I’ll be using the Windows-style root folder, C:\. If you are entering the interactive shell examples on OS X or Linux, enter
>>> myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
>>> for filename in myFiles:
        print(os.path.join('C:\\Users\\asweigart', filename))
C:\Users\asweigart\accounts.txt
C:\Users\asweigart\details.csv
C:\Users\asweigart\invite.docx
9 instead.

Khối lượng bổ sung, chẳng hạn như ổ đĩa DVD hoặc ổ đĩa ngón tay cái USB, sẽ xuất hiện khác nhau trên các hệ điều hành khác nhau. Trên Windows, chúng xuất hiện dưới dạng các ổ đĩa gốc mới, có chữ, chẳng hạn như D: \ hoặc E: \. Trên OS X, chúng xuất hiện dưới dạng các thư mục mới trong thư mục /Volume. Trên Linux, chúng xuất hiện dưới dạng các thư mục mới trong thư mục /MNT (MOUNT MOUNT). Cũng lưu ý rằng trong khi tên thư mục và tên tệp không nhạy cảm với Windows và OS X, nhưng chúng rất nhạy cảm với Linux.volumes, such as a DVD drive or USB thumb drive, will appear differently on different operating systems. On Windows, they appear as new, lettered root drives, such as D:\ or E:\. On OS X, they appear as new folders under the /Volumes folder. On Linux, they appear as new folders under the /mnt (“mount”) folder. Also note that while folder names and filenames are not case sensitive on Windows and OS X, they are case sensitive on Linux.

Backslash trên Windows và Slash chuyển tiếp trên OS X và Linux

Trên Windows, các đường dẫn được viết bằng cách sử dụng dấu gạch chéo ngược (\) làm dấu phân cách giữa các tên thư mục. Tuy nhiên, OS X và Linux sử dụng dấu gạch chéo chuyển tiếp (/) làm dấu phân cách đường dẫn của chúng. Nếu bạn muốn các chương trình của mình hoạt động trên tất cả các hệ điều hành, bạn sẽ phải viết các tập lệnh Python của mình để xử lý cả hai trường hợp.\) as the separator between folder names. OS X and Linux, however, use the forward slash (/) as their path separator. If you want your programs to work on all operating systems, you will have to write your Python scripts to handle both cases.

May mắn thay, điều này là đơn giản để làm với chức năng

>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
0. Nếu bạn chuyển nó, các giá trị chuỗi của tên tệp và tên thư mục riêng lẻ trong đường dẫn của bạn,
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
0 sẽ trả về một chuỗi với đường dẫn tệp bằng cách sử dụng các dấu phân cách đường dẫn chính xác. Nhập phần sau vào vỏ tương tác:

>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'

Tôi đã chạy các ví dụ shell tương tác này trên Windows, vì vậy

>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
2 đã trả về
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
3. .

Hàm Os.Path.join () rất hữu ích nếu bạn cần tạo chuỗi cho tên tệp. Các chuỗi này sẽ được chuyển cho một số chức năng liên quan đến tệp được giới thiệu trong chương này. Ví dụ: ví dụ sau tham gia tên từ danh sách các tên tệp đến cuối tên thư mục:

>>> myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
>>> for filename in myFiles:
        print(os.path.join('C:\\Users\\asweigart', filename))
C:\Users\asweigart\accounts.txt
C:\Users\asweigart\details.csv
C:\Users\asweigart\invite.docx

Thư mục làm việc hiện tại

Mỗi chương trình chạy trên máy tính của bạn đều có thư mục làm việc hiện tại hoặc CWD. Bất kỳ tên tệp hoặc đường dẫn nào không bắt đầu với thư mục gốc đều được coi là thuộc thư mục làm việc hiện tại. Bạn có thể nhận thư mục làm việc hiện tại dưới dạng giá trị chuỗi với hàm

>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
5 và thay đổi nó với
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
6. Nhập phần sau vào vỏ tương tác:current working directory, or cwd. Any filenames or paths that do not begin with the root folder are assumed to be under the current working directory. You can get the current working directory as a string value with the
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
5 function and change it with
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
6. Enter the following into the interactive shell:

>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'

Ở đây, thư mục làm việc hiện tại được đặt thành C: \ Python34, vì vậy dự án fileName.docx đề cập đến C: \ Python34 \ Project.docx. Khi chúng tôi thay đổi thư mục làm việc hiện tại thành C: \ Windows, Project.docx được hiểu là C: \ Windows \ Project.Docx.C:\Python34, so the filename project.docx refers to C:\Python34\project.docx. When we change the current working directory to C:\Windows, project.docx is interpreted as C:\ Windows\project.docx.

Python sẽ hiển thị một lỗi nếu bạn cố gắng thay đổi thành một thư mục không tồn tại.

>>> os.chdir('C:\\ThisFolderDoesNotExist')
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    os.chdir('C:\\ThisFolderDoesNotExist')
FileNotFoundError: [WinError 2] The system cannot find the file specified:
'C:\\ThisFolderDoesNotExist'

Ghi chú

Mặc dù thư mục là tên hiện đại hơn cho thư mục, lưu ý rằng thư mục làm việc hiện tại (hoặc chỉ thư mục làm việc) là thuật ngữ tiêu chuẩn, không phải thư mục làm việc hiện tại. current working directory (or just working directory) is the standard term, not current working folder.

Đường dẫn tuyệt đối so với tương đối

Có hai cách để chỉ định một đường dẫn tệp.

  • Một con đường tuyệt đối, luôn bắt đầu với thư mục gốcabsolute path, which always begins with the root folder

  • Một đường dẫn tương đối, liên quan đến thư mục làm việc hiện tại của chương trìnhrelative path, which is relative to the program’s current working directory

Ngoài ra còn có các thư mục DOT (

>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
7) và DOT-DOT (
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
8). Đây không phải là các thư mục thực sự nhưng những cái tên đặc biệt có thể được sử dụng trong một đường dẫn. Một khoảng thời gian duy nhất (Dot dot,) cho một tên thư mục là tốc ký cho thư mục này. Hai giai đoạn (Dot dot-dot) có nghĩa là thư mục cha mẹ.dot (
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
7) and dot-dot (
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
8) folders. These are not real folders but special names that can be used in a path. A single period (“dot”) for a folder name is shorthand for “this directory.” Two periods (“dot-dot”) means “the parent folder.”

Hình & NBSP; 8-2 là một ví dụ về một số thư mục và tệp. Khi thư mục làm việc hiện tại được đặt thành C: \ Bacon, các đường dẫn tương đối cho các thư mục và tệp khác được đặt như trong hình.C:\bacon, the relative paths for the other folders and files are set as they are in the figure.

Hướng dẫn open file using absolute path python - mở tệp bằng python đường dẫn tuyệt đối

Hình & NBSP; 8-2. & NBSP; Các đường dẫn tương đối cho các thư mục và tệp trong thư mục làm việc C: \ BaconC:\bacon

. \ Khi bắt đầu một đường dẫn tương đối là tùy chọn. Ví dụ:. \ Spam.txt và spam.txt tham khảo cùng một tệp..\ at the start of a relative path is optional. For example, .\spam.txt and spam.txt refer to the same file.

Tạo các thư mục mới với OS.MADEDIRS ()

Các chương trình của bạn có thể tạo các thư mục mới (thư mục) với chức năng

>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
9. Nhập phần sau vào vỏ tương tác:

>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')

Điều này sẽ tạo ra không chỉ thư mục C: \ Delicious mà còn là một thư mục Walnut bên trong C: \ Delicious và một thư mục Waffles bên trong C: \ Delicious \ Walnut. Đó là,

>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
9 sẽ tạo ra bất kỳ thư mục trung gian cần thiết nào để đảm bảo rằng đường dẫn đầy đủ tồn tại. Hình & nbsp; 8-3 cho thấy hệ thống phân cấp thư mục này.C:\delicious folder but also a walnut folder inside C:\delicious and a waffles folder inside C:\delicious\walnut. That is,
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
9 will create any necessary intermediate folders in order to ensure that the full path exists. Figure 8-3 shows this hierarchy of folders.

Hướng dẫn open file using absolute path python - mở tệp bằng python đường dẫn tuyệt đối

Hình & nbsp; 8-3. & Nbsp; kết quả của

>>> os.chdir('C:\\ThisFolderDoesNotExist')
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    os.chdir('C:\\ThisFolderDoesNotExist')
FileNotFoundError: [WinError 2] The system cannot find the file specified:
'C:\\ThisFolderDoesNotExist'
1

Mô -đun OS.Path

Mô -đun

>>> os.chdir('C:\\ThisFolderDoesNotExist')
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    os.chdir('C:\\ThisFolderDoesNotExist')
FileNotFoundError: [WinError 2] The system cannot find the file specified:
'C:\\ThisFolderDoesNotExist'
2 chứa nhiều chức năng hữu ích liên quan đến tên tệp và đường dẫn tệp. Chẳng hạn, bạn đã sử dụng
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
0 để xây dựng các đường dẫn theo cách sẽ hoạt động trên bất kỳ hệ điều hành nào. Vì
>>> os.chdir('C:\\ThisFolderDoesNotExist')
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    os.chdir('C:\\ThisFolderDoesNotExist')
FileNotFoundError: [WinError 2] The system cannot find the file specified:
'C:\\ThisFolderDoesNotExist'
2 là một mô -đun bên trong mô -đun
>>> myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
>>> for filename in myFiles:
        print(os.path.join('C:\\Users\\asweigart', filename))
C:\Users\asweigart\accounts.txt
C:\Users\asweigart\details.csv
C:\Users\asweigart\invite.docx
4, bạn có thể nhập nó bằng cách chạy
>>> os.chdir('C:\\ThisFolderDoesNotExist')
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    os.chdir('C:\\ThisFolderDoesNotExist')
FileNotFoundError: [WinError 2] The system cannot find the file specified:
'C:\\ThisFolderDoesNotExist'
6. Bất cứ khi nào các chương trình của bạn cần làm việc với các tệp, thư mục hoặc đường dẫn tệp, bạn có thể tham khảo các ví dụ ngắn trong phần này. Tài liệu đầy đủ cho mô -đun
>>> os.chdir('C:\\ThisFolderDoesNotExist')
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    os.chdir('C:\\ThisFolderDoesNotExist')
FileNotFoundError: [WinError 2] The system cannot find the file specified:
'C:\\ThisFolderDoesNotExist'
2 có trên trang web Python tại http://docs.python.org/3/l Library/os.path.html.http://docs.python.org/3/library/os.path.html.

Ghi chú

Hầu hết các ví dụ theo sau trong phần này sẽ yêu cầu mô -đun

>>> myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
>>> for filename in myFiles:
        print(os.path.join('C:\\Users\\asweigart', filename))
C:\Users\asweigart\accounts.txt
C:\Users\asweigart\details.csv
C:\Users\asweigart\invite.docx
4, vì vậy hãy nhớ nhập nó khi bắt đầu bất kỳ tập lệnh nào bạn viết và bất cứ khi nào bạn khởi động lại IDLE. Nếu không, bạn sẽ nhận được thông báo lỗi
>>> os.chdir('C:\\ThisFolderDoesNotExist')
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    os.chdir('C:\\ThisFolderDoesNotExist')
FileNotFoundError: [WinError 2] The system cannot find the file specified:
'C:\\ThisFolderDoesNotExist'
9.
>>> myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
>>> for filename in myFiles:
        print(os.path.join('C:\\Users\\asweigart', filename))
C:\Users\asweigart\accounts.txt
C:\Users\asweigart\details.csv
C:\Users\asweigart\invite.docx
4 module, so remember to import it at the beginning of any script you write and any time you restart IDLE. Otherwise, you’ll get a
>>> os.chdir('C:\\ThisFolderDoesNotExist')
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    os.chdir('C:\\ThisFolderDoesNotExist')
FileNotFoundError: [WinError 2] The system cannot find the file specified:
'C:\\ThisFolderDoesNotExist'
9 error message.

Xử lý các đường dẫn tuyệt đối và tương đối

Mô -đun

>>> os.chdir('C:\\ThisFolderDoesNotExist')
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    os.chdir('C:\\ThisFolderDoesNotExist')
FileNotFoundError: [WinError 2] The system cannot find the file specified:
'C:\\ThisFolderDoesNotExist'
2 cung cấp các chức năng để trả về đường dẫn tuyệt đối của đường dẫn tương đối và kiểm tra xem một đường dẫn nhất định có phải là đường dẫn tuyệt đối hay không.

  • Gọi

    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    1
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    2
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    3 sẽ trả về một chuỗi đường dẫn tuyệt đối của đối số. Đây là một cách dễ dàng để chuyển đổi một đường dẫn tương đối thành một con đường tuyệt đối.
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    2
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    3 will return a string of the absolute path of the argument. This is an easy way to convert a relative path into an absolute one.

  • Gọi

    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    4
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    2
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    3 sẽ trả về
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    7 nếu đối số là một đường dẫn tuyệt đối và
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    8 nếu đó là một đường dẫn tương đối.
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    2
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    3 will return
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    7 if the argument is an absolute path and
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    8 if it is a relative path.

  • Gọi

    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    9
    >>> os.path.abspath('.')
    'C:\\Python34'
    >>> os.path.abspath('.\\Scripts')
    'C:\\Python34\\Scripts'
    >>> os.path.isabs('.')
    False
    >>> os.path.isabs(os.path.abspath('.'))
    True
    0
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    3 sẽ trả lại một chuỗi đường dẫn tương đối từ đường dẫn
    >>> os.path.abspath('.')
    'C:\\Python34'
    >>> os.path.abspath('.\\Scripts')
    'C:\\Python34\\Scripts'
    >>> os.path.isabs('.')
    False
    >>> os.path.isabs(os.path.abspath('.'))
    True
    2 đến
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    2. Nếu
    >>> os.path.abspath('.')
    'C:\\Python34'
    >>> os.path.abspath('.\\Scripts')
    'C:\\Python34\\Scripts'
    >>> os.path.isabs('.')
    False
    >>> os.path.isabs(os.path.abspath('.'))
    True
    2 không được cung cấp, thư mục làm việc hiện tại được sử dụng làm đường dẫn bắt đầu.
    >>> os.path.abspath('.')
    'C:\\Python34'
    >>> os.path.abspath('.\\Scripts')
    'C:\\Python34\\Scripts'
    >>> os.path.isabs('.')
    False
    >>> os.path.isabs(os.path.abspath('.'))
    True
    0
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    3 will return a string of a relative path from the
    >>> os.path.abspath('.')
    'C:\\Python34'
    >>> os.path.abspath('.\\Scripts')
    'C:\\Python34\\Scripts'
    >>> os.path.isabs('.')
    False
    >>> os.path.isabs(os.path.abspath('.'))
    True
    2
    path to
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    2
    . If
    >>> os.path.abspath('.')
    'C:\\Python34'
    >>> os.path.abspath('.\\Scripts')
    'C:\\Python34\\Scripts'
    >>> os.path.isabs('.')
    False
    >>> os.path.isabs(os.path.abspath('.'))
    True
    2
    is not provided, the current working directory is used as the start path.

Hãy thử các chức năng này trong vỏ tương tác:

>>> os.path.abspath('.')
'C:\\Python34'
>>> os.path.abspath('.\\Scripts')
'C:\\Python34\\Scripts'
>>> os.path.isabs('.')
False
>>> os.path.isabs(os.path.abspath('.'))
True

Vì C: \ Python34 là thư mục làm việc khi

>>> os.path.abspath('.')
'C:\\Python34'
>>> os.path.abspath('.\\Scripts')
'C:\\Python34\\Scripts'
>>> os.path.isabs('.')
False
>>> os.path.isabs(os.path.abspath('.'))
True
5 được gọi, thư mục DOT DOT của Cameron đại diện cho đường dẫn tuyệt đối
>>> os.path.abspath('.')
'C:\\Python34'
>>> os.path.abspath('.\\Scripts')
'C:\\Python34\\Scripts'
>>> os.path.isabs('.')
False
>>> os.path.isabs(os.path.abspath('.'))
True
6.C:\Python34 was the working directory when
>>> os.path.abspath('.')
'C:\\Python34'
>>> os.path.abspath('.\\Scripts')
'C:\\Python34\\Scripts'
>>> os.path.isabs('.')
False
>>> os.path.isabs(os.path.abspath('.'))
True
5 was called, the “single-dot” folder represents the absolute path
>>> os.path.abspath('.')
'C:\\Python34'
>>> os.path.abspath('.\\Scripts')
'C:\\Python34\\Scripts'
>>> os.path.isabs('.')
False
>>> os.path.isabs(os.path.abspath('.'))
True
6.

Ghi chú

Vì hệ thống của bạn có thể có các tệp và thư mục khác nhau trên đó, bạn đã giành được chính xác mọi ví dụ trong chương này. Tuy nhiên, hãy cố gắng theo dõi bằng cách sử dụng các thư mục tồn tại trên máy tính của bạn.

Nhập các cuộc gọi sau vào

>>> os.path.abspath('.')
'C:\\Python34'
>>> os.path.abspath('.\\Scripts')
'C:\\Python34\\Scripts'
>>> os.path.isabs('.')
False
>>> os.path.isabs(os.path.abspath('.'))
True
7 vào vỏ tương tác:

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
0

Gọi

>>> os.path.abspath('.')
'C:\\Python34'
>>> os.path.abspath('.\\Scripts')
'C:\\Python34\\Scripts'
>>> os.path.isabs('.')
False
>>> os.path.isabs(os.path.abspath('.'))
True
8
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
2
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
3 sẽ trả lại một chuỗi mọi thứ diễn ra trước lần chém cuối cùng trong đối số
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
2. Gọi
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
022____82
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
3 sẽ trả lại một chuỗi mọi thứ xuất hiện sau lần chém cuối cùng trong đối số
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
2. Tên dir và tên cơ sở của một đường dẫn được phác thảo trong Hình & NBSP; 8-4.
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
2
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
3 will return a string of everything that comes before the last slash in the
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
2 argument. Calling
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
02
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
2
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
3 will return a string of everything that comes after the last slash in the
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
2 argument. The dir name and base name of a path are outlined in Figure 8-4.

Hướng dẫn open file using absolute path python - mở tệp bằng python đường dẫn tuyệt đối

Hình & nbsp; 8-4. & Nbsp; tên cơ sở theo dấu vết cuối cùng trong một đường dẫn và giống như tên tệp. Tên Dir là tất cả mọi thứ trước khi chém cuối cùng.

Ví dụ: nhập phần sau vào vỏ tương tác:

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
1

Nếu bạn cần một tên Dir Dir và tên cơ sở cùng nhau, bạn chỉ có thể gọi

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
06 để nhận giá trị tuple với hai chuỗi này, như vậy:

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
2

Lưu ý rằng bạn có thể tạo cùng một tuple bằng cách gọi

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
07 và
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
08 và đặt các giá trị trả về của chúng thành một tuple.

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
3

Nhưng

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
06 là một phím tắt đẹp nếu bạn cần cả hai giá trị.

Ngoài ra, lưu ý rằng

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
06 không đi theo đường dẫn tệp và trả về danh sách các chuỗi của mỗi thư mục. Đối với điều đó, sử dụng phương thức chuỗi
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
11 và chia trên chuỗi trong
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
12. Nhớ lại trước đó rằng biến
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
12 được đặt thành dấu gạch chéo phân tách thư mục chính xác cho máy tính chạy chương trình.not take a file path and return a list of strings of each folder. For that, use the
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
11 string method and split on the string in
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
12. Recall from earlier that the
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
12 variable is set to the correct folder-separating slash for the computer running the program.

Ví dụ: nhập phần sau vào vỏ tương tác:

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
4

Trên hệ thống OS X và Linux, sẽ có một chuỗi trống khi bắt đầu danh sách được trả về:

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
5

Phương thức chuỗi

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
11 sẽ hoạt động để trả về danh sách từng phần của đường dẫn. Nó sẽ hoạt động trên bất kỳ hệ điều hành nào nếu bạn vượt qua nó
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
15.

Tìm kích thước tệp và nội dung thư mục

Khi bạn có cách xử lý các đường dẫn tệp, sau đó bạn có thể bắt đầu thu thập thông tin về các tệp và thư mục cụ thể. Mô -đun

>>> os.chdir('C:\\ThisFolderDoesNotExist')
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    os.chdir('C:\\ThisFolderDoesNotExist')
FileNotFoundError: [WinError 2] The system cannot find the file specified:
'C:\\ThisFolderDoesNotExist'
2 cung cấp các chức năng để tìm kích thước của tệp tính bằng byte và các tệp và thư mục bên trong một thư mục nhất định.

  • Gọi

    "/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
    
    17
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    2
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    3 sẽ trả về kích thước trong byte của tệp trong đối số
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    2.
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    2
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    3 will return the size in bytes of the file in the
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    2
    argument.

  • Gọi

    "/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
    
    21
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    2
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    3 sẽ trả về danh sách các chuỗi tên tệp cho mỗi tệp trong đối số
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    2. (Lưu ý rằng hàm này nằm trong mô -đun
    >>> myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
    >>> for filename in myFiles:
            print(os.path.join('C:\\Users\\asweigart', filename))
    C:\Users\asweigart\accounts.txt
    C:\Users\asweigart\details.csv
    C:\Users\asweigart\invite.docx
    4, không phải
    >>> os.chdir('C:\\ThisFolderDoesNotExist')
    Traceback (most recent call last):
      File "<pyshell#18>", line 1, in <module>
        os.chdir('C:\\ThisFolderDoesNotExist')
    FileNotFoundError: [WinError 2] The system cannot find the file specified:
    'C:\\ThisFolderDoesNotExist'
    2.)
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    2
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    3 will return a list of filename strings for each file in the
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    2
    argument. (Note that this function is in the
    >>> myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
    >>> for filename in myFiles:
            print(os.path.join('C:\\Users\\asweigart', filename))
    C:\Users\asweigart\accounts.txt
    C:\Users\asweigart\details.csv
    C:\Users\asweigart\invite.docx
    4 module, not
    >>> os.chdir('C:\\ThisFolderDoesNotExist')
    Traceback (most recent call last):
      File "<pyshell#18>", line 1, in <module>
        os.chdir('C:\\ThisFolderDoesNotExist')
    FileNotFoundError: [WinError 2] The system cannot find the file specified:
    'C:\\ThisFolderDoesNotExist'
    2.)

Đây là những gì tôi nhận được khi tôi thử các chức năng này trong vỏ tương tác:

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
6

Như bạn có thể thấy, chương trình calc.exe trên máy tính của tôi có kích thước 776.192 byte và tôi có rất nhiều tệp trong C: \ Windows \ System32. Nếu tôi muốn tìm tổng kích thước của tất cả các tệp trong thư mục này, tôi có thể sử dụng

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
27 và
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
28 cùng nhau.calc.exe program on my computer is 776,192 bytes in size, and I have a lot of files in C:\Windows\system32. If I want to find the total size of all the files in this directory, I can use
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
27 and
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
28 together.

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
7

Khi tôi lặp qua mỗi tên tệp trong thư mục C: \ Windows \ System32, biến

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
29 được tăng theo kích thước của mỗi tệp. Lưu ý cách khi tôi gọi
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
27, tôi sử dụng
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
0 để tham gia tên thư mục với tên tệp hiện tại. Số nguyên mà
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
27 trả về được thêm vào giá trị của
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
29. Sau khi lặp qua tất cả các tệp, tôi in
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
29 để xem tổng kích thước của thư mục C: \ Windows \ System32.C:\Windows\System32 folder, the
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
29 variable is incremented by the size of each file. Notice how when I call
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
27, I use
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
0 to join the folder name with the current filename. The integer that
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
27 returns is added to the value of
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
29. After looping through all the files, I print
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
29 to see the total size of the C:\Windows\System32 folder.

Kiểm tra tính hợp lệ của đường dẫn

Nhiều chức năng Python sẽ gặp lỗi nếu bạn cung cấp cho chúng một đường dẫn không tồn tại. Mô -đun

>>> os.chdir('C:\\ThisFolderDoesNotExist')
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    os.chdir('C:\\ThisFolderDoesNotExist')
FileNotFoundError: [WinError 2] The system cannot find the file specified:
'C:\\ThisFolderDoesNotExist'
2 cung cấp các chức năng để kiểm tra xem một đường dẫn nhất định có tồn tại hay không và liệu đó là tệp hoặc thư mục.

  • Gọi

    "/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
    
    36
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    2
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    3 sẽ trả về
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    7 nếu tệp hoặc thư mục được đề cập trong đối số tồn tại và sẽ trả về
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    8 nếu nó không tồn tại.
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    2
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    3 will return
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    7 if the file or folder referred to in the argument exists and will return
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    8 if it does not exist.

  • Gọi

    "/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
    
    41
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    2
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    3 sẽ trả về
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    7 nếu đối số đường dẫn tồn tại và là một tệp và sẽ trả về
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    8 nếu không.
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    2
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    3 will return
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    7 if the path argument exists and is a file and will return
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    8 otherwise.

  • Gọi

    "/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
    
    46
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    2
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    3 sẽ trả về
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    7 nếu đối số đường dẫn tồn tại và là một thư mục và sẽ trả về
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    8 nếu không.
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    2
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    3 will return
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    7 if the path argument exists and is a folder and will return
    >>> import os
    >>> os.makedirs('C:\\delicious\\walnut\\waffles')
    8 otherwise.

Đây là những gì tôi nhận được khi tôi thử các chức năng này trong vỏ tương tác:

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
8

Như bạn có thể thấy, chương trình calc.exe trên máy tính của tôi có kích thước 776.192 byte và tôi có rất nhiều tệp trong C: \ Windows \ System32. Nếu tôi muốn tìm tổng kích thước của tất cả các tệp trong thư mục này, tôi có thể sử dụng

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
27 và
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
28 cùng nhau.D:\ on my Windows computer, I could do that with the following:

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
9

Khi tôi lặp qua mỗi tên tệp trong thư mục C: \ Windows \ System32, biến

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
29 được tăng theo kích thước của mỗi tệp. Lưu ý cách khi tôi gọi
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
27, tôi sử dụng
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
0 để tham gia tên thư mục với tên tệp hiện tại. Số nguyên mà
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
27 trả về được thêm vào giá trị của
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
29. Sau khi lặp qua tất cả các tệp, tôi in
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
29 để xem tổng kích thước của thư mục C: \ Windows \ System32.

Kiểm tra tính hợp lệ của đường dẫn

Nhiều chức năng Python sẽ gặp lỗi nếu bạn cung cấp cho chúng một đường dẫn không tồn tại. Mô -đun

>>> os.chdir('C:\\ThisFolderDoesNotExist')
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    os.chdir('C:\\ThisFolderDoesNotExist')
FileNotFoundError: [WinError 2] The system cannot find the file specified:
'C:\\ThisFolderDoesNotExist'
2 cung cấp các chức năng để kiểm tra xem một đường dẫn nhất định có tồn tại hay không và liệu đó là tệp hoặc thư mục.Plaintext files contain only basic text characters and do not include font, size, or color information. Text files with the .txt extension or Python script files with the .py extension are examples of plaintext files. These can be opened with Windows’s Notepad or OS X’s TextEdit application. Your programs can easily read the contents of plaintext files and treat them as an ordinary string value.

Gọi

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
36
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
2
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
3 sẽ trả về
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
7 nếu tệp hoặc thư mục được đề cập trong đối số tồn tại và sẽ trả về
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
8 nếu nó không tồn tại. are all other file types, such as word processing documents, PDFs, images, spreadsheets, and executable programs. If you open a binary file in Notepad or TextEdit, it will look like scrambled nonsense, like in Figure 8-5.

Hướng dẫn open file using absolute path python - mở tệp bằng python đường dẫn tuyệt đối

Gọi

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
41
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
2
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
3 sẽ trả về
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
7 nếu đối số đường dẫn tồn tại và là một tệp và sẽ trả về
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
8 nếu không.

Gọi

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
46
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
2
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
3 sẽ trả về
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
7 nếu đối số đường dẫn tồn tại và là một thư mục và sẽ trả về
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
8 nếu không.

Bạn có thể xác định xem có ổ đĩa DVD hoặc Flash hiện được gắn vào máy tính hay không bằng cách kiểm tra nó với chức năng

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
51. Chẳng hạn, nếu tôi muốn kiểm tra ổ đĩa flash với âm lượng có tên D: \ trên máy tính Windows của tôi, tôi có thể làm điều đó với những điều sau đây:

  1. Ối! Có vẻ như tôi đã quên cắm vào ổ đĩa flash của mình.

  2. Quá trình đọc/ghi tệp

  3. Đóng tệp bằng cách gọi phương thức

    "/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
    
    59 trên đối tượng
    "/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
    
    55.

Mở tệp với hàm Open ()

Để mở một tệp với hàm

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
54, bạn chuyển nó một đường dẫn chuỗi cho biết tệp bạn muốn mở; Nó có thể là một con đường tuyệt đối hoặc tương đối. Hàm
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
54 trả về một đối tượng
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
55.

Hãy thử nó bằng cách tạo một tệp văn bản có tên hello.txt bằng Notepad hoặc Textedit. Nhập

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
64 làm nội dung của tệp văn bản này và lưu nó trong thư mục nhà người dùng của bạn. Sau đó, nếu bạn sử dụng Windows, hãy nhập phần sau vào vỏ tương tác:hello.txt using Notepad or TextEdit. Type
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
64
as the content of this text file and save it in your user home folder. Then, if you’re using Windows, enter the following into the interactive shell:

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
0

Nếu bạn sử dụng OS X, thay vào đó hãy nhập phần sau vào vỏ tương tác: thay vào đó:

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
1

Đảm bảo thay thế

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
65 bằng tên người dùng máy tính của bạn. Ví dụ: tên người dùng của tôi là Asweigart, vì vậy tôi đã nhập
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
66 trên Windows.
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
65
with your computer username. For example, my username is asweigart, so I’d enter
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
66 on Windows.

Cả hai lệnh này sẽ mở tệp trong chế độ đọc Plaintext, hoặc viết tắt chế độ đọc. Khi một tệp được mở ở chế độ đọc, Python cho phép bạn chỉ đọc dữ liệu từ tệp; Bạn có thể viết hoặc sửa đổi nó theo bất kỳ cách nào. Chế độ đọc là chế độ mặc định cho các tệp bạn mở trong Python. Nhưng nếu bạn không muốn dựa vào mặc định của Python, bạn có thể chỉ định rõ ràng chế độ bằng cách chuyển giá trị chuỗi

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
67 làm đối số thứ hai cho
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
54. Vì vậy,
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
69 và
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
70 làm điều tương tự.read mode for short. When a file is opened in read mode, Python lets you only read data from the file; you can’t write or modify it in any way. Read mode is the default mode for files you open in Python. But if you don’t want to rely on Python’s defaults, you can explicitly specify the mode by passing the string value
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
67 as a second argument to
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
54. So
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
69 and
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
70 do the same thing.

Cuộc gọi đến

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
54 trả về một đối tượng
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
55. Đối tượng
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
55 đại diện cho một tệp trên máy tính của bạn; Nó chỉ đơn giản là một loại giá trị khác trong Python, giống như các danh sách và từ điển mà bạn đã quen thuộc. Trong ví dụ trước, bạn đã lưu trữ đối tượng
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
55 trong biến
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
75. Bây giờ, bất cứ khi nào bạn muốn đọc từ hoặc ghi vào tệp, bạn có thể làm như vậy bằng cách gọi các phương thức trên đối tượng
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
55 trong
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
75.

Đọc nội dung của các tệp

Bây giờ bạn có một đối tượng

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
55, bạn có thể bắt đầu đọc từ nó. Nếu bạn muốn đọc toàn bộ nội dung của một tệp dưới dạng giá trị chuỗi, hãy sử dụng phương thức
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
55 đối tượng ____ ____156. Hãy để tiếp tục với đối tượng Hello.txt
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
55 mà bạn đã lưu trữ trong
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
75. Nhập phần sau vào vỏ tương tác:hello.txt
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
55 object you stored in
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
75. Enter the following into the interactive shell:

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
2

Nếu bạn nghĩ về nội dung của một tệp dưới dạng một giá trị chuỗi lớn duy nhất, phương thức

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
56 sẽ trả về chuỗi được lưu trữ trong tệp.

Ngoài ra, bạn có thể sử dụng phương thức

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
84 để lấy danh sách các giá trị chuỗi từ tệp, một chuỗi cho mỗi dòng văn bản. Ví dụ: tạo một tệp có tên Sonnet29.txt trong cùng thư mục với Hello.txt và viết văn bản sau trong đó:list of string values from the file, one string for each line of text. For example, create a file named sonnet29.txt in the same directory as hello.txt and write the following text in it:

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
3

Hãy chắc chắn để tách bốn dòng với các đường ngắt. Sau đó nhập phần sau vào vỏ tương tác:

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
4

Lưu ý rằng mỗi giá trị chuỗi kết thúc bằng một ký tự mới,

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
85, ngoại trừ dòng cuối cùng của tệp. Một danh sách các chuỗi thường dễ làm việc hơn một giá trị chuỗi lớn duy nhất.

Viết vào các tập tin

Python cho phép bạn viết nội dung vào một tệp theo cách tương tự như cách hàm

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
86, viết các chuỗi trên màn hình. Mặc dù vậy, bạn có thể viết thư cho một tập tin mà bạn đã mở ở chế độ đọc. Thay vào đó, bạn cần phải mở nó trong chế độ viết văn bản của Write Write hoặc chế độ nối liền với chế độ của bản rõ, hoặc chế độ ghi và chế độ nối ngắn.write mode and append mode for short.

Chế độ ghi sẽ ghi đè lên tệp hiện có và bắt đầu từ đầu, giống như khi bạn ghi đè lên giá trị biến biến có giá trị mới. Vượt qua

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
87 làm đối số thứ hai cho
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
54 để mở tệp ở chế độ ghi. Mặt khác, chế độ nối thêm văn bản sẽ nối văn bản vào cuối tệp hiện có. Bạn có thể nghĩ về điều này là nối vào một danh sách trong một biến, thay vì ghi đè hoàn toàn biến. Vượt qua
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
89 làm đối số thứ hai cho
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
54 để mở tệp ở chế độ nối.

Nếu tên tệp được chuyển đến

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
54 không tồn tại, cả chế độ ghi và nối sẽ tạo một tệp mới, trống. Sau khi đọc hoặc viết tệp, hãy gọi phương thức
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
59 trước khi mở tệp.

Hãy để các khái niệm này lại với nhau. Nhập phần sau vào vỏ tương tác:

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
5

Đầu tiên, chúng tôi mở Bacon.txt trong chế độ ghi. Vì có một Bacon.txt chưa, Python tạo ra một. Gọi

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
57 trên tệp đã mở và truyền
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
57 đối số chuỗi
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
95 ghi chuỗi vào tệp và trả về số lượng ký tự được viết, bao gồm cả dòng mới. Sau đó, chúng tôi đóng tệp.bacon.txt in write mode. Since there isn’t a bacon.txt yet, Python creates one. Calling
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
57 on the opened file and passing
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
57 the string argument
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
95 writes the string to the file and returns the number of characters written, including the newline. Then we close the file.

Để thêm văn bản vào các nội dung hiện có của tệp thay vì thay thế chuỗi chúng tôi vừa viết, chúng tôi mở tệp ở chế độ phụ lục. Chúng tôi viết

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
96 vào tệp và đóng nó. Cuối cùng, để in nội dung tệp vào màn hình, chúng tôi mở tệp ở chế độ đọc mặc định của nó, gọi
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
56, lưu trữ đối tượng
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
55 trong
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
99, đóng tệp và in
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
99.

Lưu ý rằng phương thức

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
57 không tự động thêm ký tự dòng mới vào cuối chuỗi như hàm
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
86. Bạn sẽ phải tự thêm nhân vật này.

Lưu các biến với mô -đun kệ

Bạn có thể lưu các biến trong các chương trình Python của mình vào các tệp kệ nhị phân bằng mô -đun

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
53. Bằng cách này, chương trình của bạn có thể khôi phục dữ liệu về các biến từ ổ cứng. Mô -đun
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
53 sẽ cho phép bạn thêm các tính năng lưu và mở vào chương trình của mình. Ví dụ: nếu bạn đã chạy một chương trình và nhập một số cài đặt cấu hình, bạn có thể lưu các cài đặt đó vào tệp kệ và sau đó tải chúng vào lần tiếp theo.

Nhập phần sau vào vỏ tương tác:

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
6

Để đọc và ghi dữ liệu bằng mô -đun

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
53, trước tiên bạn nhập
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
53. Gọi
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
07 và chuyển nó một tên tệp, sau đó lưu trữ giá trị kệ được trả về trong một biến. Bạn có thể thay đổi giá trị kệ như thể nó là một từ điển. Khi bạn hoàn thành, hãy gọi
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
59 trên giá trị kệ. Ở đây, giá trị kệ của chúng tôi được lưu trữ trong
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
09. Chúng tôi tạo một danh sách
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
10 và viết
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
11 để lưu trữ danh sách trong
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
09 dưới dạng giá trị liên quan đến khóa
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
13 (như trong từ điển). Sau đó, chúng tôi gọi
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
59 vào
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
09.

Sau khi chạy mã trước trên Windows, bạn sẽ thấy ba tệp mới trong thư mục làm việc hiện tại: MyData.Bak, MyData.Dat và MyData.Dir. Trên OS X, chỉ có một tệp mydata.db duy nhất sẽ được tạo.mydata.bak, mydata.dat, and mydata.dir. On OS X, only a single mydata.db file will be created.

Các tệp nhị phân này chứa dữ liệu bạn lưu trữ trong kệ của bạn. Định dạng của các tệp nhị phân này không quan trọng; Bạn chỉ cần biết mô -đun

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
53 làm gì, chứ không phải nó làm như thế nào. Mô -đun giải phóng bạn khỏi lo lắng về cách lưu trữ dữ liệu chương trình của bạn vào một tệp.

Các chương trình của bạn có thể sử dụng mô -đun

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
53 để mở lại và truy xuất dữ liệu từ các tệp kệ này. Các giá trị kệ don lồng phải được mở trong chế độ đọc hoặc viết, họ có thể thực hiện cả hai khi được mở. Nhập phần sau vào vỏ tương tác:

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
7

Ở đây, chúng tôi mở các tệp kệ để kiểm tra xem dữ liệu của chúng tôi có được lưu trữ chính xác không. Nhập

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
18 Trả về cùng một danh sách mà chúng tôi đã lưu trữ trước đó, vì vậy chúng tôi biết rằng danh sách được lưu trữ chính xác và chúng tôi gọi
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
59.

Giống như từ điển, các giá trị kệ có các phương thức

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
20 và
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
21 sẽ trả về các giá trị giống như danh sách của các khóa và giá trị trong kệ. Vì các phương thức này trả về các giá trị giống như danh sách thay vì danh sách thực sự, bạn nên chuyển chúng đến hàm
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
22 để đưa chúng ở dạng danh sách. Nhập phần sau vào vỏ tương tác:

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
8

PlainText rất hữu ích cho việc tạo các tệp mà bạn sẽ đọc trong trình chỉnh sửa văn bản như Notepad hoặc Textedit, nhưng nếu bạn muốn lưu dữ liệu từ các chương trình Python của mình, hãy sử dụng mô -đun

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
53.

Lưu các biến với hàm pprint.pformat ()

Nhớ lại từ In Printing rằng hàm

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
24 sẽ in khá đẹp các nội dung của danh sách hoặc từ điển lên màn hình, trong khi hàm
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
25 sẽ trả về cùng văn bản này như một chuỗi thay vì in nó. Chuỗi này không chỉ được định dạng để dễ đọc, mà còn là mã Python chính xác về mặt cú pháp. Giả sử bạn có một từ điển được lưu trữ trong một biến và bạn muốn lưu biến này và nội dung của nó để sử dụng trong tương lai. Sử dụng
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
25 sẽ cung cấp cho bạn một chuỗi mà bạn có thể ghi vào tệp .py. Tệp này sẽ là mô -đun rất riêng của bạn mà bạn có thể nhập bất cứ khi nào bạn muốn sử dụng biến được lưu trữ trong đó..py file. This file will be your very own module that you can import whenever you want to use the variable stored in it.

Ví dụ: nhập phần sau vào vỏ tương tác:

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
9

Ở đây, chúng tôi nhập

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
27 để cho chúng tôi sử dụng
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
25. Chúng tôi có một danh sách các từ điển, được lưu trữ trong một biến
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
10. Để giữ danh sách trong
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
10 có sẵn ngay cả sau khi chúng tôi đóng vỏ, chúng tôi sử dụng
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
25 để trả về nó dưới dạng chuỗi. Khi chúng tôi có dữ liệu trong
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
10 dưới dạng chuỗi, nó dễ dàng ghi chuỗi vào một tệp, mà chúng tôi sẽ gọi mycats.py.myCats.py.

Các mô -đun mà một câu lệnh

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
33 nhập khẩu chỉ là các tập lệnh Python. Khi chuỗi từ
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
25 được lưu vào tệp .py, tệp là một mô -đun có thể được nhập giống như bất kỳ mô -đun nào khác..py file, the file is a module that can be imported just like any other.

Và vì các tập lệnh Python chỉ là các tệp văn bản với phần mở rộng tệp .py, các chương trình Python của bạn thậm chí có thể tạo ra các chương trình Python khác. Sau đó, bạn có thể nhập các tệp này vào tập lệnh..py file extension, your Python programs can even generate other Python programs. You can then import these files into scripts.

"/Users/<username>/Documents/github/main_folder/first_folder/second_folder/readme.txt"
0

Lợi ích của việc tạo tệp .py (trái ngược với việc lưu các biến với mô -đun

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
53) là vì nó là tệp văn bản, nội dung của tệp có thể được đọc và sửa đổi bởi bất kỳ ai có trình chỉnh sửa văn bản đơn giản. Tuy nhiên, đối với hầu hết các ứng dụng, lưu dữ liệu bằng mô -đun
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
53 là cách ưa thích để lưu các biến vào tệp. Chỉ các loại dữ liệu cơ bản như số nguyên, phao, chuỗi, danh sách và từ điển mới có thể được ghi vào một tệp dưới dạng văn bản đơn giản. Ví dụ, các đối tượng
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
55 không thể được mã hóa dưới dạng văn bản..py file (as opposed to saving variables with the
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
53 module) is that because it is a text file, the contents of the file can be read and modified by anyone with a simple text editor. For most applications, however, saving data using the
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
53 module is the preferred way to save variables to a file. Only basic data types such as integers, floats, strings, lists, and dictionaries can be written to a file as simple text.
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
55 objects, for example, cannot be encoded as text.

Dự án: Tạo các tệp đố ngẫu nhiên

Giả sử bạn là một giáo viên địa lý với 35 học sinh trong lớp và bạn muốn đưa ra một bài kiểm tra nhạc pop về thủ đô của tiểu bang Hoa Kỳ. Than ôi, lớp học của bạn có một vài quả trứng xấu trong đó và bạn có thể tin tưởng các sinh viên không gian lận. Bạn muốn chọn ngẫu nhiên thứ tự các câu hỏi để mỗi bài kiểm tra là duy nhất, khiến bất cứ ai không thể trả lời từ bất kỳ ai khác. Tất nhiên, làm điều này bằng tay sẽ là một chuyện dài và nhàm chán. May mắn thay, bạn biết một số Python.

Đây là những gì chương trình làm:

  • Tạo 35 câu đố khác nhau.

  • Tạo 50 câu hỏi trắc nghiệm cho mỗi bài kiểm tra, theo thứ tự ngẫu nhiên.

  • Cung cấp câu trả lời đúng và ba câu trả lời sai ngẫu nhiên cho mỗi câu hỏi, theo thứ tự ngẫu nhiên.

  • Viết các câu đố lên 35 tệp văn bản.

  • Viết các khóa trả lời cho 35 tệp văn bản.

Điều này có nghĩa là mã sẽ cần phải làm như sau:

  • Lưu trữ các tiểu bang và thủ đô của họ trong một từ điển.

  • Gọi

    "/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
    
    54,
    "/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
    
    57 và
    "/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
    
    59 cho bài kiểm tra và trả lời các tệp văn bản chính.

  • Sử dụng

    import os
    
    DIR_ABS_PATH = os.path.dirname(__file__)
    README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
    
    41 để chọn ngẫu nhiên thứ tự của các câu hỏi và các tùy chọn trắc nghiệm.

Bước 1: Lưu trữ dữ liệu đố trong từ điển

Bước đầu tiên là tạo tập lệnh bộ xương và điền vào dữ liệu đố của bạn. Tạo một tệp có tên RandomquizGenerator.py và làm cho nó trông giống như sau:randomQuizGenerator.py, and make it look like the following:

"/Users/<username>/Documents/github/main_folder/first_folder/second_folder/readme.txt"
1

Vì chương trình này sẽ được đặt hàng ngẫu nhiên các câu hỏi và câu trả lời, bạn sẽ cần nhập mô -đun

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
42 để sử dụng các chức năng của nó. Biến
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
43 có chứa một từ điển với các trạng thái Hoa Kỳ dưới dạng các khóa và thủ đô của họ là giá trị. Và vì bạn muốn tạo 35 câu đố, mã thực sự tạo ra bài kiểm tra và trả lời các tệp khóa (được đánh dấu bằng các nhận xét
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
44 ngay bây giờ) sẽ đi vào bên trong vòng lặp
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
45 lặp lại 35 lần. (Số này có thể được thay đổi để tạo bất kỳ số lượng tệp đố nào.)

Bước 2: Tạo tệp đố và xáo trộn thứ tự câu hỏi

Bây giờ, thời gian để bắt đầu điền vào những

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
44 đó.

Mã trong vòng lặp sẽ được lặp lại 35 lần, một lần cho mỗi bài kiểm tra, vì vậy bạn chỉ phải lo lắng về việc chỉ có một bài kiểm tra tại một thời điểm trong vòng lặp. Đầu tiên, bạn sẽ tạo tập tin đố thực tế. Nó cần phải có một tên tệp độc đáo và cũng nên có một số loại tiêu đề tiêu chuẩn trong đó, với các địa điểm để học sinh điền vào tên, ngày và giai đoạn học. Sau đó, bạn sẽ cần phải có một danh sách các trạng thái theo thứ tự ngẫu nhiên, có thể được sử dụng sau này để tạo ra các câu hỏi và câu trả lời cho bài kiểm tra.

Thêm các dòng mã sau vào RandomquizGenerator.py:randomQuizGenerator.py:

"/Users/<username>/Documents/github/main_folder/first_folder/second_folder/readme.txt"
2

Tên tệp cho các câu đố sẽ là Capitalsquiz.txt, trong đó là một số duy nhất cho bài kiểm tra xuất phát từ

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
47, bộ đếm vòng lặp
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
45. Khóa trả lời cho CapitalsQuiz.TXT sẽ được lưu trữ trong một tệp văn bản có tên Capitalsquiz_answers.txt. Mỗi lần thông qua vòng lặp, trình giữ chỗ
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
49 trong
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
50 và
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
51 sẽ được thay thế bằng
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
52, do đó, bài kiểm tra đầu tiên và khóa trả lời được tạo sẽ là capitalsquiz1.txt và capitalsquiz_answers1.txt. Các tệp này sẽ được tạo bằng các cuộc gọi đến hàm
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
54 tại ❶ và ❷, với
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
87 là đối số thứ hai để mở chúng ở chế độ ghi.capitalsquiz.txt, where is a unique number for the quiz that comes from
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
47, the
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
45 loop’s counter. The answer key for capitalsquiz.txt will be stored in a text file named capitalsquiz_answers.txt. Each time through the loop, the
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
49 placeholder in
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
50 and
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
51 will be replaced by
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
52, so the first quiz and answer key created will be capitalsquiz1.txt and capitalsquiz_answers1.txt. These files will be created with calls to the
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
54 function at ❶ and ❷, with
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
87 as the second argument to open them in write mode.

Các câu lệnh

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
57 tại ❸ Tạo tiêu đề đố vui cho học sinh điền vào. Cuối cùng, một danh sách ngẫu nhiên của các trạng thái Hoa Kỳ được tạo ra với sự trợ giúp của hàm
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
41, sắp xếp lại ngẫu nhiên các giá trị trong bất kỳ danh sách nào được truyền cho nó.

Bước 3: Tạo các tùy chọn trả lời

Bây giờ bạn cần tạo các tùy chọn trả lời cho mỗi câu hỏi, đây sẽ là nhiều lựa chọn từ A đến D. Bạn sẽ cần phải tạo một vòng lặp

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
45 khác để tạo nội dung cho mỗi trong số 50 câu hỏi trong bài kiểm tra. Sau đó, sẽ có một vòng lặp
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
45 thứ ba được lồng bên trong để tạo các tùy chọn trắc nghiệm cho mỗi câu hỏi. Làm cho mã của bạn trông giống như sau:

"/Users/<username>/Documents/github/main_folder/first_folder/second_folder/readme.txt"
3

Câu trả lời đúng rất dễ nhận được, nó được lưu trữ dưới dạng giá trị trong từ điển

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
43. Vòng lặp này sẽ lặp qua các trạng thái trong danh sách
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
60 xáo trộn, từ
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
61 đến
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
62, tìm mỗi trạng thái trong
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
43 và lưu trữ vốn tương ứng của bang trong
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
64.

Danh sách các câu trả lời sai có thể là khó khăn hơn. Bạn có thể nhận được nó bằng cách sao chép tất cả các giá trị trong từ điển

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
43, xóa câu trả lời đúng và chọn ba giá trị ngẫu nhiên từ danh sách này. Hàm
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
66 giúp dễ dàng thực hiện lựa chọn này. Đối số đầu tiên của nó là danh sách bạn muốn chọn từ; Đối số thứ hai là số lượng giá trị bạn muốn chọn. Danh sách đầy đủ các tùy chọn trả lời là sự kết hợp của ba câu trả lời sai này với câu trả lời chính xác. Cuối cùng, các câu trả lời cần được chọn ngẫu nhiên để phản hồi chính xác không phải lúc nào cũng được lựa chọn D.all the values in the
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
43 dictionary ❷, deleting the correct answer ❸, and selecting three random values from this list ❹. The
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
66 function makes it easy to do this selection. Its first argument is the list you want to select from; the second argument is the number of values you want to select. The full list of answer options is the combination of these three wrong answers with the correct answers ❺. Finally, the answers need to be randomized ❻ so that the correct response isn’t always choice D.

Bước 4: Viết nội dung vào bài kiểm tra và trả lời các tệp khóa

Tất cả những gì còn lại là viết câu hỏi vào tệp đố và câu trả lời cho tệp khóa trả lời. Làm cho mã của bạn trông giống như sau:

"/Users/<username>/Documents/github/main_folder/first_folder/second_folder/readme.txt"
4

Một vòng lặp

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
45 đi qua các số nguyên
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
68 đến
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
69 sẽ viết các tùy chọn trả lời trong danh sách
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
70. Biểu thức
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
71 tại ❷ coi chuỗi
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
72 là một mảng và sẽ đánh giá thành ________ 273, ________ 274,
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
75, sau đó
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
76 trên mỗi lần lặp tương ứng thông qua vòng lặp.

Trong dòng cuối cùng, biểu thức

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
77 sẽ tìm thấy chỉ số số nguyên của câu trả lời đúng trong các tùy chọn trả lời được đặt hàng ngẫu nhiên và
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
78 sẽ đánh giá cho thư trả lời đúng được ghi vào tệp chính trả lời.

Sau khi bạn chạy chương trình, đây là cách mà tệp capitalsquiz1.txt của bạn sẽ xem xét, mặc dù tất nhiên các tùy chọn câu hỏi và câu trả lời của bạn có thể khác với các câu hỏi được hiển thị ở đây, tùy thuộc vào kết quả của các cuộc gọi

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
41 của bạn:capitalsquiz1.txt file will look, though of course your questions and answer options may be different from those shown here, depending on the outcome of your
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
41 calls:

"/Users/<username>/Documents/github/main_folder/first_folder/second_folder/readme.txt"
5

Tệp văn bản Capitalsquiz_answers1.txt tương ứng sẽ trông như thế này:capitalsquiz_answers1.txt text file will look like this:

"/Users/<username>/Documents/github/main_folder/first_folder/second_folder/readme.txt"
6

Dự án: Multiclipboard

Giả sử bạn có nhiệm vụ nhàm chán là điền vào nhiều biểu mẫu trong một trang web hoặc phần mềm với một số trường văn bản. Clipboard giúp bạn không gõ cùng một văn bản nhiều lần. Nhưng chỉ có một điều có thể có trên bảng tạm cùng một lúc. Nếu bạn có một số đoạn văn bản khác nhau mà bạn cần sao chép và dán, bạn phải tiếp tục làm nổi bật và sao chép các điều tương tự nhiều lần.

Bạn có thể viết một chương trình Python để theo dõi nhiều đoạn văn bản. Bảng điều khiển đa lớp này sẽ được đặt tên là MCB.PYW (vì MC MCB có thể gõ ngắn hơn so với bảng điều khiển multicboard). Tiện ích mở rộng .PYW có nghĩa là Python đã giành được một cửa sổ thiết bị đầu cuối khi nó chạy chương trình này. (Xem Phụ lục B để biết thêm chi tiết.)mcb.pyw (since “mcb” is shorter to type than “multiclipboard”). The .pyw extension means that Python won’t show a Terminal window when it runs this program. (See Appendix B for more details.)

Chương trình sẽ lưu từng đoạn văn bản clipboard dưới một từ khóa. Ví dụ: khi bạn chạy

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
80, nội dung hiện tại của bảng tạm sẽ được lưu bằng thư rác từ khóa. Văn bản này sau đó có thể được tải vào bảng tạm bằng cách chạy
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
81. Và nếu người dùng quên những từ khóa họ có, họ có thể chạy
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
82 để sao chép danh sách tất cả các từ khóa vào bảng tạm.spam. This text can later be loaded to the clipboard again by running
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
81. And if the user forgets what keywords they have, they can run
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
82 to copy a list of all keywords to the clipboard.

Đây là những gì chương trình làm:

  • Đối số dòng lệnh cho từ khóa được kiểm tra.

  • Nếu đối số là

    import os
    
    DIR_ABS_PATH = os.path.dirname(__file__)
    README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
    
    83, thì nội dung bảng tạm được lưu vào từ khóa.

  • Nếu đối số là

    import os
    
    DIR_ABS_PATH = os.path.dirname(__file__)
    README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
    
    84, thì tất cả các từ khóa được sao chép vào bảng tạm.

  • Mặt khác, văn bản cho từ khóa được sao chép vào bảng tạm.

Điều này có nghĩa là mã sẽ cần phải làm như sau:

  • Đọc các đối số dòng lệnh từ

    import os
    
    DIR_ABS_PATH = os.path.dirname(__file__)
    README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
    
    85.

  • Đọc và viết vào bảng tạm.

  • Lưu và tải vào một tập tin kệ.

Nếu bạn sử dụng Windows, bạn có thể dễ dàng chạy tập lệnh này từ cửa sổ chạy ... bằng cách tạo tệp hàng loạt có tên MCB.BAT với nội dung sau:mcb.bat with the following content:

"/Users/<username>/Documents/github/main_folder/first_folder/second_folder/readme.txt"
7

Bước 1: Nhận xét và thiết lập kệ

Hãy bắt đầu bằng cách tạo một kịch bản bộ xương với một số nhận xét và thiết lập cơ bản. Làm cho mã của bạn trông giống như sau:

"/Users/<username>/Documents/github/main_folder/first_folder/second_folder/readme.txt"
8

Nó thực hành phổ biến để đưa thông tin sử dụng chung vào các bình luận ở đầu tệp. Nếu bạn quên cách chạy tập lệnh của mình, bạn luôn có thể nhìn vào những bình luận này để nhắc nhở. Sau đó, bạn nhập các mô -đun của bạn. Sao chép và dán sẽ yêu cầu mô -đun

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
86 và đọc các đối số dòng lệnh sẽ yêu cầu mô -đun
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
87. Mô -đun
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
53 cũng sẽ có ích: bất cứ khi nào người dùng muốn lưu một đoạn văn bản clipboard mới, bạn sẽ lưu nó vào tệp kệ. Sau đó, khi người dùng muốn dán văn bản trở lại bảng tạm của họ, bạn sẽ mở tệp kệ và tải lại vào chương trình của bạn. Tệp kệ sẽ được đặt tên với tiền tố MCB.mcb ❸.

Bước 2: Lưu nội dung Clipboard bằng từ khóa

Chương trình thực hiện những điều khác nhau tùy thuộc vào việc người dùng muốn lưu văn bản vào từ khóa, tải văn bản vào bảng tạm hay liệt kê tất cả các từ khóa hiện có. Hãy để đối phó với trường hợp đầu tiên đó. Làm cho mã của bạn trông giống như sau:

"/Users/<username>/Documents/github/main_folder/first_folder/second_folder/readme.txt"
9

Nếu đối số dòng lệnh đầu tiên (sẽ luôn ở chỉ mục

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
89 của danh sách
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
85) là
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
91, đối số dòng lệnh thứ hai là từ khóa cho nội dung hiện tại của bảng tạm. Từ khóa sẽ được sử dụng làm khóa cho
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
92 và giá trị sẽ là văn bản hiện tại trên bảng tạm.

Nếu chỉ có một đối số dòng lệnh, bạn sẽ cho rằng đó là

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
93 hoặc từ khóa để tải nội dung lên bảng tạm. Bạn sẽ thực hiện mã đó sau. Hiện tại, chỉ cần đặt một bình luận
import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
44 ở đó.

Bước 3: Liệt kê các từ khóa và tải nội dung từ khóa

Cuối cùng, hãy để Lừa thực hiện hai trường hợp còn lại: Người dùng muốn tải văn bản Clipboard từ một từ khóa hoặc họ muốn có danh sách tất cả các từ khóa có sẵn. Làm cho mã của bạn trông giống như sau:

>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
0

Nếu chỉ có một đối số dòng lệnh, trước tiên hãy để, hãy kiểm tra xem nó có phải là

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
93 hay không. Nếu vậy, một biểu diễn chuỗi của danh sách các phím kệ sẽ được sao chép vào bảng tạm. Người dùng có thể dán danh sách này vào một trình soạn thảo văn bản mở để đọc nó.

Nếu không, bạn có thể giả sử đối số dòng lệnh là một từ khóa. Nếu từ khóa này tồn tại trong kệ

import os

DIR_ABS_PATH = os.path.dirname(__file__)
README_PATH = os.path.join(DIR_ABS_PATH, 'second_folder', 'readme.txt')
92 làm khóa, bạn có thể tải giá trị lên bảng tạm.

Và đó là nó! Ra mắt chương trình này có các bước khác nhau tùy thuộc vào hệ điều hành mà máy tính của bạn sử dụng. Xem Phụ lục B để biết chi tiết cho hệ điều hành của bạn.

Nhớ lại chương trình khóa mật khẩu mà bạn đã tạo trong Chương & NBSP; 6 đã lưu trữ mật khẩu trong từ điển. Cập nhật mật khẩu yêu cầu thay đổi mã nguồn của chương trình. Đây là lý tưởng vì người dùng trung bình don don cảm thấy thoải mái khi thay đổi mã nguồn để cập nhật phần mềm của họ. Ngoài ra, mỗi khi bạn sửa đổi mã nguồn thành một chương trình, bạn có nguy cơ vô tình giới thiệu các lỗi mới. Bằng cách lưu trữ dữ liệu cho một chương trình ở một nơi khác với mã, bạn có thể giúp các chương trình của mình dễ dàng sử dụng và chống lỗi hơn.

Bản tóm tắt

Các tệp được tổ chức thành các thư mục (còn được gọi là thư mục) và một đường dẫn mô tả vị trí của một tệp. Mỗi chương trình chạy trên máy tính của bạn đều có thư mục làm việc hiện tại, cho phép bạn chỉ định các đường dẫn tệp liên quan đến vị trí hiện tại thay vì luôn gõ đường dẫn đầy đủ (hoặc tuyệt đối). Mô -đun

>>> os.chdir('C:\\ThisFolderDoesNotExist')
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    os.chdir('C:\\ThisFolderDoesNotExist')
FileNotFoundError: [WinError 2] The system cannot find the file specified:
'C:\\ThisFolderDoesNotExist'
2 có nhiều chức năng để thao tác các đường dẫn tệp.

Các chương trình của bạn cũng có thể tương tác trực tiếp với nội dung của các tệp văn bản. Hàm

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
54 có thể mở các tệp này để đọc trong nội dung của chúng dưới dạng một chuỗi lớn (với phương thức
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
56) hoặc dưới dạng danh sách các chuỗi (với phương thức
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
84). Hàm
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
54 có thể mở các tệp ở chế độ ghi hoặc nối để tạo các tệp văn bản mới hoặc thêm vào các tệp văn bản hiện có.

Trong các chương trước, bạn đã sử dụng bảng tạm như một cách để nhận một lượng lớn văn bản vào một chương trình, thay vì gõ tất cả. ít biến động hơn nhiều so với bảng tạm.

Trong chương tiếp theo, bạn sẽ học cách tự xử lý các tệp, bằng cách sao chép chúng, xóa chúng, đổi tên chúng, di chuyển chúng và hơn thế nữa.

Thực hành câu hỏi

Q:

1. Một con đường tương đối là gì so với?

Q:

2. Một con đường tuyệt đối bắt đầu từ gì?

Q:

3. Các chức năng

>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
5 và
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
6 làm gì?

Q:

4. Các thư mục

>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
7 và
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
8 là gì?

Q:

5. Trong C: \ Bacon \ Eggs \ spam.txt, phần nào là tên dir, và phần nào là tên cơ sở?C:\bacon\eggs\spam.txt, which part is the dir name, and which part is the base name?

Q:

6. Ba đối số của chế độ có thể được truyền đến hàm

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
54 là gì?

Q:

7. Điều gì xảy ra nếu một tệp hiện có được mở ở chế độ ghi?

Q:

8. Sự khác biệt giữa các phương pháp

"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
56 và
"/Users/<username>/Documents/github/main_folder/first_folder/first_file.py"
84 là gì?

Q:

9. Cấu trúc dữ liệu nào giá trị kệ giống với?

Thực hành các dự án

Để thực hành, thiết kế và viết các chương trình sau.

Mở rộng bảng đa sáng

Mở rộng chương trình Multiclipboard trong chương này để nó có đối số dòng lệnh

"/Users/<username>/Documents/github/main_folder/first_folder/second_folder/readme.txt"
09 sẽ xóa một từ khóa khỏi kệ. Sau đó thêm một đối số dòng lệnh
"/Users/<username>/Documents/github/main_folder/first_folder/second_folder/readme.txt"
10 sẽ xóa tất cả các từ khóa.all keywords.

Libs điên

Tạo một chương trình MAD LIBS đọc trong các tệp văn bản và cho phép người dùng thêm văn bản của riêng họ bất cứ nơi nào từ tính từ, danh từ, trạng từ hoặc động từ xuất hiện trong tệp văn bản. Ví dụ: tệp văn bản có thể trông như thế này:ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file. For example, a text file may look like this:

>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
1

Chương trình sẽ tìm thấy những sự xuất hiện này và nhắc nhở người dùng thay thế chúng.

>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
2

Tệp văn bản sau sau đó sẽ được tạo:

>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
3

Các kết quả nên được in lên màn hình và được lưu vào một tệp văn bản mới.

Tìm kiếm regex

Viết một chương trình mở tất cả các tệp .txt trong một thư mục và tìm kiếm bất kỳ dòng nào phù hợp với biểu thức chính quy do người dùng cung cấp. Các kết quả nên được in lên màn hình.txt files in a folder and searches for any line that matches a user-supplied regular expression. The results should be printed to the screen.

Làm cách nào để mở một con đường tuyệt đối trong Python?

Các bước để mở tập tin trong Python..
Tìm đường dẫn của một tập tin. Chúng ta có thể mở một tệp bằng cả đường dẫn tương đối và đường dẫn tuyệt đối. ....
Quyết định chế độ truy cập. ....
Vượt qua đường dẫn tệp và chế độ truy cập vào hàm Open (). ....
Đọc nội dung từ một tập tin. ....
Viết nội dung vào tệp. ....
Đóng tệp sau khi hoàn thành hoạt động ..

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 tham khảo một đường dẫn tệp trong Python?

Tham khảo một tệp trong Windows..
Python cho phép bạn sử dụng dấu gạch chéo kiểu OS-X/Linux "/" ngay cả trong Windows.....
Nếu sử dụng Backslash, vì nó là một nhân vật đặc biệt trong Python, bạn phải nhớ thoát khỏi mọi phiên bản: 'C: \\ users \\ narae \\ Desktop \\ alice ..

Con đường tuyệt đối có nghĩa là gì trong Python?

Một đường dẫn tệp tuyệt đối mô tả cách truy cập một tệp hoặc thư mục đã cho, bắt đầu từ gốc của hệ thống tệp.Một đường dẫn tệp cũng được gọi là một tên đường dẫn.Các đường dẫn tệp tương đối được ghi nhận bằng cách thiếu một dấu gạch chéo dẫn đầu.describes how to access a given file or directory, starting from the root of the file system. A file path is also called a pathname. Relative file paths are notated by a lack of a leading forward slash.