Hướng dẫn why python cannot find my file? - tại sao python không thể tìm thấy tệp của tôi?

Tôi biết đây là một câu hỏi cũ, nhưng đây là một lựa chọn khác.

Show

Đặt Parent_Folder của bạn nếu bạn có nhiều tệp trong cùng một thư mục:

parent folder = "C:/Users/User/Desktop/"

Mở rộng thư mục nếu cần thiết:

import os.path
folder = os.path.join( parent_folder, "python stuff" )

Thêm tên tệp:

file = os.path.join( folder, "Data.txt" )

Mở tập tin:

if os.path.exists( file ):
    with open( file, "r"  ) as infile:
        data = infile.read()

or:

import os
import os.path

# get the desktop location ( since this is a special folder )
desktop = os.path.join(( os.environ["userprofile"] ), "desktop" )
file = os.path.join( desktop, "python stuff", "data.txt" )
if os.path.exists( file ):
    with open( file, "r" ) as infile:
        data = infile.read()

Thư mục hiện tại của chương trình không nhất thiết là thư mục mà chương trình sống. Để làm điều này, bạn cần tìm đường dẫn đầy đủ đến chương trình của mình với sys.argv [0] và áp dụng dirname () cho nó, sau đó thay đổi thư mục thành nó:

os.chdir( dirname( sys.argv[0] ) )

Sau đó, bạn có thể mở các tệp trong cùng thư mục với chương trình.

Nó không phải là hiếm khi Pythonistas mới gặp khó khăn trong việc cài đặt các gói và sử dụng các mô -đun của chúng. Lỗi bực bội như thế này thường phát sinh, ngay cả khi bạn nghĩ rằng bạn đã cài đặt một gói đúng cách:packages and using their modules. Frustrating errors like this often arise, even if you think you’ve installed a package properly:

>>>

ImportError: No module named 

Điều này được gây ra bởi thực tế là phiên bản Python mà bạn đang chạy tập lệnh của bạn không được cấu hình để tìm kiếm các mô -đun nơi bạn đã cài đặt chúng. Điều này xảy ra khi bạn sử dụng cài đặt sai

import os
import os.path

# get the desktop location ( since this is a special folder )
desktop = os.path.join(( os.environ["userprofile"] ), "desktop" )
file = os.path.join( desktop, "python stuff", "data.txt" )
if os.path.exists( file ):
    with open( file, "r" ) as infile:
        data = infile.read()
7 để cài đặt các gói.

Nói chung, mỗi cài đặt Python đi kèm với

import os
import os.path

# get the desktop location ( since this is a special folder )
desktop = os.path.join(( os.environ["userprofile"] ), "desktop" )
file = os.path.join( desktop, "python stuff", "data.txt" )
if os.path.exists( file ):
    with open( file, "r" ) as infile:
        data = infile.read()
7 có thể thực thi riêng, được sử dụng để cài đặt các gói. Theo mặc định,
import os
import os.path

# get the desktop location ( since this is a special folder )
desktop = os.path.join(( os.environ["userprofile"] ), "desktop" )
file = os.path.join( desktop, "python stuff", "data.txt" )
if os.path.exists( file ):
    with open( file, "r" ) as infile:
        data = infile.read()
7 thực thi sẽ cài đặt các gói ở một vị trí nơi cài đặt Python cụ thể đó có thể tìm thấy chúng.

Vấn đề là rất phổ biến khi cài đặt nhiều phiên dịch viên python (và bằng cách mở rộng, nhiều ____47 thực thi.) Tùy thuộc vào đường dẫn của shell của bạn, chạy

import os
import os.path

# get the desktop location ( since this is a special folder )
desktop = os.path.join(( os.environ["userprofile"] ), "desktop" )
file = os.path.join( desktop, "python stuff", "data.txt" )
if os.path.exists( file ):
    with open( file, "r" ) as infile:
        data = infile.read()
7 có thể gọi
import os
import os.path

# get the desktop location ( since this is a special folder )
desktop = os.path.join(( os.environ["userprofile"] ), "desktop" )
file = os.path.join( desktop, "python stuff", "data.txt" )
if os.path.exists( file ):
    with open( file, "r" ) as infile:
        data = infile.read()
7 có thể liên kết với phiên bản Python mà bạn đang sử dụng hoặc cái khác. Nếu
import os
import os.path

# get the desktop location ( since this is a special folder )
desktop = os.path.join(( os.environ["userprofile"] ), "desktop" )
file = os.path.join( desktop, "python stuff", "data.txt" )
if os.path.exists( file ):
    with open( file, "r" ) as infile:
        data = infile.read()
7 sai được gọi, thì các gói mà nó cài đặt có thể sẽ không hiển thị cho trình thông dịch Python mà bạn sử dụng, gây ra
os.chdir( dirname( sys.argv[0] ) )
4.

Để sử dụng phiên bản

import os
import os.path

# get the desktop location ( since this is a special folder )
desktop = os.path.join(( os.environ["userprofile"] ), "desktop" )
file = os.path.join( desktop, "python stuff", "data.txt" )
if os.path.exists( file ):
    with open( file, "r" ) as infile:
        data = infile.read()
7 cụ thể cho phiên bản Python mong muốn của bạn, bạn có thể sử dụng
os.chdir( dirname( sys.argv[0] ) )
6. Ở đây,
os.chdir( dirname( sys.argv[0] ) )
7 là đường dẫn đến trình thông dịch Python mong muốn, vì vậy một cái gì đó như
os.chdir( dirname( sys.argv[0] ) )
8 sẽ sử dụng
import os
import os.path

# get the desktop location ( since this is a special folder )
desktop = os.path.join(( os.environ["userprofile"] ), "desktop" )
file = os.path.join( desktop, "python stuff", "data.txt" )
if os.path.exists( file ):
    with open( file, "r" ) as infile:
        data = infile.read()
7 có thể thực thi cho
ImportError: No module named 
0. Tuy nhiên, điều này vẫn có những hạn chế của nó.

Ngoài ra còn có những cách khác để đi xung quanh vấn đề này. Bạn có thể sửa đổi đường dẫn Shell Shell của mình để nó sử dụng chính xác

import os
import os.path

# get the desktop location ( since this is a special folder )
desktop = os.path.join(( os.environ["userprofile"] ), "desktop" )
file = os.path.join( desktop, "python stuff", "data.txt" )
if os.path.exists( file ):
    with open( file, "r" ) as infile:
        data = infile.read()
7 có thể thực thi hoặc thay đổi
ImportError: No module named 
2 để phiên bản Python mong muốn của bạn có thể tìm thấy các gói nằm trong một thư mục khác. Nhưng tất cả những điều này có thể trở nên lộn xộn nhanh chóng.

Thay vào đó, môi trường ảo thường được sử dụng để cô lập các cài đặt Python với nhau. Một môi trường ảo chứa, trong số những thứ khác, một trình thông dịch Python, thực thi

import os
import os.path

# get the desktop location ( since this is a special folder )
desktop = os.path.join(( os.environ["userprofile"] ), "desktop" )
file = os.path.join( desktop, "python stuff", "data.txt" )
if os.path.exists( file ):
    with open( file, "r" ) as infile:
        data = infile.read()
7 và thư mục gói trang web, là vị trí tiêu chuẩn cho hầu hết các gói được tải xuống với
import os
import os.path

# get the desktop location ( since this is a special folder )
desktop = os.path.join(( os.environ["userprofile"] ), "desktop" )
file = os.path.join( desktop, "python stuff", "data.txt" )
if os.path.exists( file ):
    with open( file, "r" ) as infile:
        data = infile.read()
7.virtual environments are often used to isolate Python installations from one another. A virtual environment contains, among other things, a Python interpreter, a
import os
import os.path

# get the desktop location ( since this is a special folder )
desktop = os.path.join(( os.environ["userprofile"] ), "desktop" )
file = os.path.join( desktop, "python stuff", "data.txt" )
if os.path.exists( file ):
    with open( file, "r" ) as infile:
        data = infile.read()
7 executable, and a site-packages directory, which is the standard location for most packages downloaded with
import os
import os.path

# get the desktop location ( since this is a special folder )
desktop = os.path.join(( os.environ["userprofile"] ), "desktop" )
file = os.path.join( desktop, "python stuff", "data.txt" )
if os.path.exists( file ):
    with open( file, "r" ) as infile:
        data = infile.read()
7.

Bằng cách kích hoạt môi trường ảo trong vỏ của bạn, bạn chỉ đưa nó đến các tệp thực thi

import os
import os.path

# get the desktop location ( since this is a special folder )
desktop = os.path.join(( os.environ["userprofile"] ), "desktop" )
file = os.path.join( desktop, "python stuff", "data.txt" )
if os.path.exists( file ):
    with open( file, "r" ) as infile:
        data = infile.read()
7 và Python được cài đặt trong môi trường ảo của bạn, đảm bảo rằng các phiên bản phù hợp của cả hai ứng dụng được gọi và các gói luôn được cài đặt vào đúng vị trí. Môi trường ảo cũng cho phép bạn chạy các phiên bản khác nhau của cùng một gói với các dự án khác nhau, điều gì đó không thể nếu bạn đang sử dụng cài đặt Python toàn cầu.

Có nhiều môi trường ảo khác nhau để lựa chọn. Khóa học này sử dụng Conda, đi kèm với Anaconda. Bạn có thể tìm hiểu thêm về môi trường ảo khi làm việc với môi trường ảo Python.Conda, bundled with Anaconda. You can learn more about virtual environments in Working With Python Virtual Environments.

Đọ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 why python cannot find my file? - tại sao python không thể tìm thấy tệp của 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

ImportError: No module named 
6 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
ImportError: No module named 
6 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

ImportError: No module named 
7. 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,
ImportError: No module named 
7 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 đang chạy các ví dụ shell tương tác này trên Windows, vì vậy

ImportError: No module named 
9 đã trả về
>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
0. .

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.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
2 và thay đổi nó với
>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
3. 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.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
2 function and change it with
>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
3. 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.

import os.path
folder = os.path.join( parent_folder, "python stuff" )
0

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.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
4) và DOT-DOT (
>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
5). Đâ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.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
4) and dot-dot (
>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
5) 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 why python cannot find my file? - tại sao python không thể tìm thấy tệp của 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 hàm

>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
6. Nhập phần sau vào vỏ tương tác:

import os.path
folder = os.path.join( parent_folder, "python stuff" )
1

Đ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.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
6 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.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
6 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 why python cannot find my file? - tại sao python không thể tìm thấy tệp của tôi?

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

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

Mô -đun OS.Path

Mô -đun

>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
9 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
ImportError: No module named 
7 để 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ì
>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
9 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
2, bạn có thể nhập nó bằng cách chạy
>>> 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
3. 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
>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
9 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
2, 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
>>> 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.
>>> 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 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
>>> 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 error message.

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

Mô -đun

>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
9 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

    >>> 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
    8
    >>> 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
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    0 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.
    >>> 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
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    0 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.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    1
    >>> 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
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    0 sẽ trả về
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    4 nếu đối số là một đường dẫn tuyệt đối và
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    5 nếu đó là một đường dẫn tương đối.
    >>> 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
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    0 will return
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    4 if the argument is an absolute path and
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    5 if it is a relative path.

  • Gọi

    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    6
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    7
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    0 sẽ trả lại một chuỗi đường dẫn tương đối từ đường dẫn
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    9 đế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
    9. Nếu
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    9 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.
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    7
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    0 will return a string of a relative path from the
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    9
    path to
    >>> 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
    . If
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    9
    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:

import os.path
folder = os.path.join( parent_folder, "python stuff" )
2

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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
02 được gọi, thư mục DOT DOT của Cameron đại diện cho đường dẫn tuyệt đối
import os.path
folder = os.path.join( parent_folder, "python stuff" )
03.C:\Python34 was the working directory when
import os.path
folder = os.path.join( parent_folder, "python stuff" )
02 was called, the “single-dot” folder represents the absolute path
import os.path
folder = os.path.join( parent_folder, "python stuff" )
03.

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
2, 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
>>> 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.

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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
3

Mô -đun

>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
9 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.
>>> 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
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
0 will return a string of everything that comes before the last slash 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
9 argument. Calling
import os.path
folder = os.path.join( parent_folder, "python stuff" )
09
>>> 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
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
0 will return a string of everything that comes after the last slash 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
9 argument. The dir name and base name of a path are outlined in Figure 8-4.

Hướng dẫn why python cannot find my file? - tại sao python không thể tìm thấy tệp của tôi?

Gọi

>>> 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
8
>>> 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
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
0 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.

Gọi

>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
1
>>> 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
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
0 sẽ trả về
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
4 nếu đối số là một đường dẫn tuyệt đối và
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
5 nếu đó là một đường dẫn tương đối.

import os.path
folder = os.path.join( parent_folder, "python stuff" )
4

Gọi

>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
6
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
7
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
0 sẽ trả lại một chuỗi đường dẫn tương đối từ đường dẫn
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
9 đế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
9. Nếu
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
9 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.

import os.path
folder = os.path.join( parent_folder, "python stuff" )
5

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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
6

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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
02 được gọi, thư mục DOT DOT của Cameron đại diện cho đường dẫn tuyệt đối
import os.path
folder = os.path.join( parent_folder, "python stuff" )
03.

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.not take a file path and return a list of strings of each folder. For that, use the

import os.path
folder = os.path.join( parent_folder, "python stuff" )
18 string method and split on the string in
import os.path
folder = os.path.join( parent_folder, "python stuff" )
19. Recall from earlier that the
import os.path
folder = os.path.join( parent_folder, "python stuff" )
19 variable is set to the correct folder-separating slash for the computer running the program.

Gọi

>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
1
>>> 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
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
0 sẽ trả về
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
4 nếu đối số là một đường dẫn tuyệt đối và
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
5 nếu đó là một đường dẫn tương đối.

import os.path
folder = os.path.join( parent_folder, "python stuff" )
7

Gọi

>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
6
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
7
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
0 sẽ trả lại một chuỗi đường dẫn tương đối từ đường dẫn
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
9 đế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
9. Nếu
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
9 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.

import os.path
folder = os.path.join( parent_folder, "python stuff" )
8

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

Vì C: \ Python34 là thư mục làm việc khi import os.path folder = os.path.join( parent_folder, "python stuff" ) 02 được gọi, thư mục DOT DOT của Cameron đại diện cho đường dẫn tuyệt đối import os.path folder = os.path.join( parent_folder, "python stuff" ) 03.

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.

  • Gọi

    import os.path
    folder = os.path.join( parent_folder, "python stuff" )
    
    24
    >>> 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
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    0 sẽ trả về kích thước trong byte của tệp trong đối số
    >>> 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.
    >>> 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
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    0 will return the size in bytes of the file 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
    9
    argument.

  • Gọi

    import os.path
    folder = os.path.join( parent_folder, "python stuff" )
    
    28
    >>> 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
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    0 sẽ trả về danh sách các chuỗi tên tệp cho mỗi tệp trong đối số
    >>> 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. (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
    2, không phải
    >>> import os
    >>> os.path.join('usr', 'bin', 'spam')
    'usr\\bin\\spam'
    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
    9
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    0 will return a list of filename strings for each file 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
    9
    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
    2 module, not
    >>> import os
    >>> os.path.join('usr', 'bin', 'spam')
    'usr\\bin\\spam'
    9.)

Đâ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:

import os.path
folder = os.path.join( parent_folder, "python stuff" )
9

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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
34 và
import os.path
folder = os.path.join( parent_folder, "python stuff" )
35 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
import os.path
folder = os.path.join( parent_folder, "python stuff" )
34 and
import os.path
folder = os.path.join( parent_folder, "python stuff" )
35 together.

file = os.path.join( folder, "Data.txt" )
0

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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
36 được tăng lên theo kích thước của mỗi tệp. Lưu ý cách khi tôi gọi
import os.path
folder = os.path.join( parent_folder, "python stuff" )
34, tôi sử dụng
ImportError: No module named 
7 để tham gia tên thư mục với tên tệp hiện tại. Số nguyên mà
import os.path
folder = os.path.join( parent_folder, "python stuff" )
34 trả về được thêm vào giá trị của
import os.path
folder = os.path.join( parent_folder, "python stuff" )
36. Sau khi lặp qua tất cả các tệp, tôi in
import os.path
folder = os.path.join( parent_folder, "python stuff" )
36 để xem tổng kích thước của thư mục C: \ Windows \ System32.C:\Windows\System32 folder, the
import os.path
folder = os.path.join( parent_folder, "python stuff" )
36 variable is incremented by the size of each file. Notice how when I call
import os.path
folder = os.path.join( parent_folder, "python stuff" )
34, I use
ImportError: No module named 
7 to join the folder name with the current filename. The integer that
import os.path
folder = os.path.join( parent_folder, "python stuff" )
34 returns is added to the value of
import os.path
folder = os.path.join( parent_folder, "python stuff" )
36. After looping through all the files, I print
import os.path
folder = os.path.join( parent_folder, "python stuff" )
36 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

>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
9 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

    import os.path
    folder = os.path.join( parent_folder, "python stuff" )
    
    43
    >>> 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
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    0 sẽ trả về
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    4 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.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    5 nếu nó không tồn tại.
    >>> 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
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    0 will return
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    4 if the file or folder referred to in the argument exists and will return
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    5 if it does not exist.

  • Gọi

    import os.path
    folder = os.path.join( parent_folder, "python stuff" )
    
    48
    >>> 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
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    0 sẽ trả về
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    4 nếu đối số đường dẫn tồn tại và là một tệp và sẽ trả về
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    5 nếu không.
    >>> 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
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    0 will return
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    4 if the path argument exists and is a file and will return
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    5 otherwise.

  • Gọi

    import os.path
    folder = os.path.join( parent_folder, "python stuff" )
    
    53
    >>> 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
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    0 sẽ trả về
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    4 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.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    5 nếu không.
    >>> 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
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    0 will return
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    4 if the path argument exists and is a folder and will return
    >>> import os
    >>> os.getcwd()
    'C:\\Python34'
    >>> os.chdir('C:\\Windows\\System32')
    >>> os.getcwd()
    'C:\\Windows\\System32'
    5 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:

file = os.path.join( folder, "Data.txt" )
1

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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
34 và
import os.path
folder = os.path.join( parent_folder, "python stuff" )
35 cùng nhau.D:\ on my Windows computer, I could do that with the following:

file = os.path.join( folder, "Data.txt" )
2

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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
36 được tăng lên theo kích thước của mỗi tệp. Lưu ý cách khi tôi gọi
import os.path
folder = os.path.join( parent_folder, "python stuff" )
34, tôi sử dụng
ImportError: No module named 
7 để tham gia tên thư mục với tên tệp hiện tại. Số nguyên mà
import os.path
folder = os.path.join( parent_folder, "python stuff" )
34 trả về được thêm vào giá trị của
import os.path
folder = os.path.join( parent_folder, "python stuff" )
36. Sau khi lặp qua tất cả các tệp, tôi in
import os.path
folder = os.path.join( parent_folder, "python stuff" )
36 để 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

>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
9 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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
43
>>> 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
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
0 sẽ trả về
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
4 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.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
5 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 why python cannot find my file? - tại sao python không thể tìm thấy tệp của tôi?

Gọi

import os.path
folder = os.path.join( parent_folder, "python stuff" )
48
>>> 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
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
0 sẽ trả về
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
4 nếu đối số đường dẫn tồn tại và là một tệp và sẽ trả về
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
5 nếu không.

Gọi

import os.path
folder = os.path.join( parent_folder, "python stuff" )
53
>>> 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
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
0 sẽ trả về
>>> import os
>>> os.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
4 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.getcwd()
'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
5 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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
58. 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. Khi bạn cảm thấy thoải mái khi làm việc với các thư mục và đường dẫn tương đối, bạn sẽ có thể chỉ định vị trí của các tệp để đọc và ghi. Các chức năng được đề cập trong một vài phần tiếp theo sẽ áp dụng cho các tệp Plaintext. Các tệp Plaintext chỉ chứa các ký tự văn bản cơ bản và không bao gồm thông tin phông chữ, kích thước hoặc màu. Tệp văn bản với các tệp .TXT mở rộng hoặc tập lệnh Python với tiện ích mở rộng .Py là các ví dụ về các tệp plaintext. Chúng có thể được mở với ứng dụng Windows từ Notepad hoặc OS XTHER Textedit. Các chương trình của bạn có thể dễ dàng đọc nội dung của các tệp PlainText và coi chúng là một giá trị chuỗi thông thường.

Các tệp nhị phân là tất cả các loại tệp khác, chẳng hạn như tài liệu xử lý văn bản, PDF, hình ảnh, bảng tính và các chương trình thực thi. Nếu bạn mở một tệp nhị phân trong Notepad hoặc Textedit, nó sẽ trông giống như vô nghĩa, như trong Hình & NBSP; 8-5.

Hình & NBSP; 8-5. & NBSP; Chương trình Windows

import os.path
folder = os.path.join( parent_folder, "python stuff" )
59 được mở trong Notepad

Vì mọi loại tệp nhị phân khác nhau phải được xử lý theo cách riêng của nó, cuốn sách này sẽ không được đọc và viết trực tiếp các tệp nhị phân thô. May mắn thay, nhiều mô -đun giúp làm việc với các tệp nhị phân dễ dàng hơn, bạn sẽ khám phá một trong số chúng, mô -đun

import os.path
folder = os.path.join( parent_folder, "python stuff" )
60, sau đó trong chương này.hello.txt using Notepad or TextEdit. Type
import os.path
folder = os.path.join( parent_folder, "python stuff" )
71
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:

file = os.path.join( folder, "Data.txt" )
3

Có ba bước để đọc hoặc viết các tập tin bằng Python.

file = os.path.join( folder, "Data.txt" )
4

Gọi hàm

import os.path
folder = os.path.join( parent_folder, "python stuff" )
61 để trả về đối tượng
import os.path
folder = os.path.join( parent_folder, "python stuff" )
62.
import os.path
folder = os.path.join( parent_folder, "python stuff" )
72
with your computer username. For example, my username is asweigart, so I’d enter
import os.path
folder = os.path.join( parent_folder, "python stuff" )
73 on Windows.

Gọi phương thức

import os.path
folder = os.path.join( parent_folder, "python stuff" )
63 hoặc
import os.path
folder = os.path.join( parent_folder, "python stuff" )
64 trên đối tượng
import os.path
folder = os.path.join( parent_folder, "python stuff" )
62.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
import os.path
folder = os.path.join( parent_folder, "python stuff" )
74 as a second argument to
import os.path
folder = os.path.join( parent_folder, "python stuff" )
61. So
import os.path
folder = os.path.join( parent_folder, "python stuff" )
76 and
import os.path
folder = os.path.join( parent_folder, "python stuff" )
77 do the same thing.

Cuộc gọi đến

import os.path
folder = os.path.join( parent_folder, "python stuff" )
61 trả về một đối tượng
import os.path
folder = os.path.join( parent_folder, "python stuff" )
62. Đối tượng
import os.path
folder = os.path.join( parent_folder, "python stuff" )
62 đạ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
import os.path
folder = os.path.join( parent_folder, "python stuff" )
62 trong biến
import os.path
folder = os.path.join( parent_folder, "python stuff" )
82. 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
import os.path
folder = os.path.join( parent_folder, "python stuff" )
62 trong
import os.path
folder = os.path.join( parent_folder, "python stuff" )
82.

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

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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
62, 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 tệp dưới dạng giá trị chuỗi, hãy sử dụng phương thức
import os.path
folder = os.path.join( parent_folder, "python stuff" )
62 đối tượng
import os.path
folder = os.path.join( parent_folder, "python stuff" )
63. Hãy để tiếp tục với đối tượng Hello.txt
import os.path
folder = os.path.join( parent_folder, "python stuff" )
62 mà bạn đã lưu trữ trong
import os.path
folder = os.path.join( parent_folder, "python stuff" )
82. Nhập phần sau vào vỏ tương tác:hello.txt
import os.path
folder = os.path.join( parent_folder, "python stuff" )
62 object you stored in
import os.path
folder = os.path.join( parent_folder, "python stuff" )
82. Enter the following into the interactive shell:

file = os.path.join( folder, "Data.txt" )
5

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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
63 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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
91 để 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:

file = os.path.join( folder, "Data.txt" )
6

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:

file = os.path.join( folder, "Data.txt" )
7

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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
92, 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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
93, 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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
94 làm đối số thứ hai cho
import os.path
folder = os.path.join( parent_folder, "python stuff" )
61 để 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
import os.path
folder = os.path.join( parent_folder, "python stuff" )
96 làm đối số thứ hai cho
import os.path
folder = os.path.join( parent_folder, "python stuff" )
61 để mở tệp ở chế độ nối.

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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
61 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
import os.path
folder = os.path.join( parent_folder, "python stuff" )
66 trước khi mở tệp lại.

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:

file = os.path.join( folder, "Data.txt" )
8

Đầ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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
64 trên tệp đã mở và truyền
import os.path
folder = os.path.join( parent_folder, "python stuff" )
64 đối số chuỗi
file = os.path.join( folder, "Data.txt" )
02 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
import os.path
folder = os.path.join( parent_folder, "python stuff" )
64 on the opened file and passing
import os.path
folder = os.path.join( parent_folder, "python stuff" )
64 the string argument
file = os.path.join( folder, "Data.txt" )
02 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

file = os.path.join( folder, "Data.txt" )
03 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
import os.path
folder = os.path.join( parent_folder, "python stuff" )
63, lưu trữ đối tượng
import os.path
folder = os.path.join( parent_folder, "python stuff" )
62 trong
file = os.path.join( folder, "Data.txt" )
06, đóng tệp và in
file = os.path.join( folder, "Data.txt" )
06.

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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
64 không tự động thêm ký tự dòng mới vào cuối chuỗi như hàm
import os.path
folder = os.path.join( parent_folder, "python stuff" )
93. 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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
60. 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
import os.path
folder = os.path.join( parent_folder, "python stuff" )
60 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:

file = os.path.join( folder, "Data.txt" )
9

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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
60, trước tiên bạn nhập
import os.path
folder = os.path.join( parent_folder, "python stuff" )
60. Gọi
file = os.path.join( folder, "Data.txt" )
14 và chuyển nó một tên tệp, sau đó lưu trữ giá trị kệ được trả lại 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
import os.path
folder = os.path.join( parent_folder, "python stuff" )
66 trên giá trị kệ. Ở đây, giá trị kệ của chúng tôi được lưu trữ trong
file = os.path.join( folder, "Data.txt" )
16. Chúng tôi tạo một danh sách
file = os.path.join( folder, "Data.txt" )
17 và viết
file = os.path.join( folder, "Data.txt" )
18 để lưu trữ danh sách trong
file = os.path.join( folder, "Data.txt" )
16 dưới dạng giá trị liên quan đến khóa
file = os.path.join( folder, "Data.txt" )
20 (như trong từ điển). Sau đó, chúng tôi gọi
import os.path
folder = os.path.join( parent_folder, "python stuff" )
66 vào
file = os.path.join( folder, "Data.txt" )
16.

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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
60 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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
60 để 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:

if os.path.exists( file ):
    with open( file, "r"  ) as infile:
        data = infile.read()
0

Ở đâ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

file = os.path.join( folder, "Data.txt" )
25 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
import os.path
folder = os.path.join( parent_folder, "python stuff" )
66.

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

file = os.path.join( folder, "Data.txt" )
27 và
file = os.path.join( folder, "Data.txt" )
28 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
file = os.path.join( folder, "Data.txt" )
29 để đưa chúng ở dạng danh sách. Nhập phần sau vào vỏ tương tác:

if os.path.exists( file ):
    with open( file, "r"  ) as infile:
        data = infile.read()
1

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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
60.

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

Nhớ lại từ in đẹp rằng hàm

file = os.path.join( folder, "Data.txt" )
31 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
file = os.path.join( folder, "Data.txt" )
32 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
file = os.path.join( folder, "Data.txt" )
32 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:

if os.path.exists( file ):
    with open( file, "r"  ) as infile:
        data = infile.read()
2

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

file = os.path.join( folder, "Data.txt" )
34 để cho chúng tôi sử dụng
file = os.path.join( folder, "Data.txt" )
32. Chúng tôi có một danh sách các từ điển, được lưu trữ trong một biến
file = os.path.join( folder, "Data.txt" )
17. Để giữ danh sách trong
file = os.path.join( folder, "Data.txt" )
17 có sẵn ngay cả sau khi chúng tôi đóng vỏ, chúng tôi sử dụng
file = os.path.join( folder, "Data.txt" )
32 để trả về nó dưới dạng chuỗi. Khi chúng tôi có dữ liệu trong
file = os.path.join( folder, "Data.txt" )
17 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

file = os.path.join( folder, "Data.txt" )
40 nhập khẩu chỉ là các tập lệnh Python. Khi chuỗi từ
file = os.path.join( folder, "Data.txt" )
32 đượ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.

if os.path.exists( file ):
    with open( file, "r"  ) as infile:
        data = infile.read()
3

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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
60) 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
import os.path
folder = os.path.join( parent_folder, "python stuff" )
60 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
import os.path
folder = os.path.join( parent_folder, "python stuff" )
62 không thể được mã hóa dưới dạng văn bản..py file (as opposed to saving variables with the
import os.path
folder = os.path.join( parent_folder, "python stuff" )
60 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
import os.path
folder = os.path.join( parent_folder, "python stuff" )
60 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.
import os.path
folder = os.path.join( parent_folder, "python stuff" )
62 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

    import os.path
    folder = os.path.join( parent_folder, "python stuff" )
    
    61,
    import os.path
    folder = os.path.join( parent_folder, "python stuff" )
    
    64 và
    import os.path
    folder = os.path.join( parent_folder, "python stuff" )
    
    66 cho bài kiểm tra và trả lời các tệp văn bản chính.

  • Sử dụng

    file = os.path.join( folder, "Data.txt" )
    
    48 để 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:

if os.path.exists( file ):
    with open( file, "r"  ) as infile:
        data = infile.read()
4

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

file = os.path.join( folder, "Data.txt" )
49 để sử dụng các chức năng của nó. Biến
file = os.path.join( folder, "Data.txt" )
50 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
file = os.path.join( folder, "Data.txt" )
51 ngay bây giờ) sẽ đi vào bên trong vòng lặp
file = os.path.join( folder, "Data.txt" )
52 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

file = os.path.join( folder, "Data.txt" )
51 đó.

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:

if os.path.exists( file ):
    with open( file, "r"  ) as infile:
        data = infile.read()
5

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ừ

file = os.path.join( folder, "Data.txt" )
54, bộ đếm vòng lặp
file = os.path.join( folder, "Data.txt" )
52. 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ỗ
file = os.path.join( folder, "Data.txt" )
56 trong
file = os.path.join( folder, "Data.txt" )
57 và
file = os.path.join( folder, "Data.txt" )
58 sẽ được thay thế bằng
file = os.path.join( folder, "Data.txt" )
59, 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
import os.path
folder = os.path.join( parent_folder, "python stuff" )
61 tại ❶ và ❷, với
import os.path
folder = os.path.join( parent_folder, "python stuff" )
94 là đối số thứ hai để mở chúng ở chế độ ghi.capitalsquiz.txt, where is a unique number for the quiz that comes from
file = os.path.join( folder, "Data.txt" )
54, the
file = os.path.join( folder, "Data.txt" )
52 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
file = os.path.join( folder, "Data.txt" )
56 placeholder in
file = os.path.join( folder, "Data.txt" )
57 and
file = os.path.join( folder, "Data.txt" )
58 will be replaced by
file = os.path.join( folder, "Data.txt" )
59, 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
import os.path
folder = os.path.join( parent_folder, "python stuff" )
61 function at ❶ and ❷, with
import os.path
folder = os.path.join( parent_folder, "python stuff" )
94 as the second argument to open them in write mode.

Các câu lệnh

import os.path
folder = os.path.join( parent_folder, "python stuff" )
64 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
file = os.path.join( folder, "Data.txt" )
48, 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

file = os.path.join( folder, "Data.txt" )
52 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
file = os.path.join( folder, "Data.txt" )
52 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:

if os.path.exists( file ):
    with open( file, "r"  ) as infile:
        data = infile.read()
6

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

file = os.path.join( folder, "Data.txt" )
50. Vòng lặp này sẽ lặp qua các trạng thái trong danh sách
file = os.path.join( folder, "Data.txt" )
67 xáo trộn, từ
file = os.path.join( folder, "Data.txt" )
68 đến
file = os.path.join( folder, "Data.txt" )
69, tìm mỗi trạng thái trong
file = os.path.join( folder, "Data.txt" )
50 và lưu trữ vốn tương ứng của bang trong
file = os.path.join( folder, "Data.txt" )
71.

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

file = os.path.join( folder, "Data.txt" )
50, 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
file = os.path.join( folder, "Data.txt" )
73 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
file = os.path.join( folder, "Data.txt" )
50 dictionary ❷, deleting the correct answer ❸, and selecting three random values from this list ❹. The
file = os.path.join( folder, "Data.txt" )
73 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:

if os.path.exists( file ):
    with open( file, "r"  ) as infile:
        data = infile.read()
7

Một vòng lặp

file = os.path.join( folder, "Data.txt" )
52 đi qua các số nguyên
file = os.path.join( folder, "Data.txt" )
75 đến
file = os.path.join( folder, "Data.txt" )
76 sẽ viết các tùy chọn trả lời trong danh sách
file = os.path.join( folder, "Data.txt" )
77. Biểu thức
file = os.path.join( folder, "Data.txt" )
78 tại ❷ coi chuỗi
file = os.path.join( folder, "Data.txt" )
79 là một mảng và sẽ đánh giá thành ________ 280, ________ 281,
file = os.path.join( folder, "Data.txt" )
82, sau đó
file = os.path.join( folder, "Data.txt" )
83 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

file = os.path.join( folder, "Data.txt" )
84 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à
file = os.path.join( folder, "Data.txt" )
85 sẽ đánh giá cho thư trả lời đúng để được ghi vào tệp khóa 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

file = os.path.join( folder, "Data.txt" )
48 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
file = os.path.join( folder, "Data.txt" )
48 calls:

if os.path.exists( file ):
    with open( file, "r"  ) as infile:
        data = infile.read()
8

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:

if os.path.exists( file ):
    with open( file, "r"  ) as infile:
        data = infile.read()
9

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

file = os.path.join( folder, "Data.txt" )
87, 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
file = os.path.join( folder, "Data.txt" )
88. Và nếu người dùng quên những từ khóa họ có, họ có thể chạy
file = os.path.join( folder, "Data.txt" )
89 để 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
file = os.path.join( folder, "Data.txt" )
88. And if the user forgets what keywords they have, they can run
file = os.path.join( folder, "Data.txt" )
89 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à

    file = os.path.join( folder, "Data.txt" )
    
    90, thì nội dung Clipboard sẽ được lưu vào từ khóa.

  • Nếu đối số là

    file = os.path.join( folder, "Data.txt" )
    
    91, 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ừ

    file = os.path.join( folder, "Data.txt" )
    
    92.

  • Đọ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:

import os
import os.path

# get the desktop location ( since this is a special folder )
desktop = os.path.join(( os.environ["userprofile"] ), "desktop" )
file = os.path.join( desktop, "python stuff", "data.txt" )
if os.path.exists( file ):
    with open( file, "r" ) as infile:
        data = infile.read()
0

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:

import os
import os.path

# get the desktop location ( since this is a special folder )
desktop = os.path.join(( os.environ["userprofile"] ), "desktop" )
file = os.path.join( desktop, "python stuff", "data.txt" )
if os.path.exists( file ):
    with open( file, "r" ) as infile:
        data = infile.read()
1

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

file = os.path.join( folder, "Data.txt" )
93 và đọc các đối số dòng lệnh sẽ yêu cầu mô -đun
file = os.path.join( folder, "Data.txt" )
94. Mô -đun
import os.path
folder = os.path.join( parent_folder, "python stuff" )
60 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:

import os
import os.path

# get the desktop location ( since this is a special folder )
desktop = os.path.join(( os.environ["userprofile"] ), "desktop" )
file = os.path.join( desktop, "python stuff", "data.txt" )
if os.path.exists( file ):
    with open( file, "r" ) as infile:
        data = infile.read()
2

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

file = os.path.join( folder, "Data.txt" )
96 của danh sách
file = os.path.join( folder, "Data.txt" )
92) là
file = os.path.join( folder, "Data.txt" )
98, đố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
file = os.path.join( folder, "Data.txt" )
99 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à

if os.path.exists( file ):
    with open( file, "r"  ) as infile:
        data = infile.read()
00 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
file = os.path.join( folder, "Data.txt" )
51 ở đó.

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
import os.path

# get the desktop location ( since this is a special folder )
desktop = os.path.join(( os.environ["userprofile"] ), "desktop" )
file = os.path.join( desktop, "python stuff", "data.txt" )
if os.path.exists( file ):
    with open( file, "r" ) as infile:
        data = infile.read()
3

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à

if os.path.exists( file ):
    with open( file, "r"  ) as infile:
        data = infile.read()
00 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ệ

file = os.path.join( folder, "Data.txt" )
99 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

>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
9 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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
61 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
import os.path
folder = os.path.join( parent_folder, "python stuff" )
63) hoặc dưới dạng danh sách các chuỗi (với phương thức
import os.path
folder = os.path.join( parent_folder, "python stuff" )
91). Hàm
import os.path
folder = os.path.join( parent_folder, "python stuff" )
61 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.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
2 và
>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
3 làm gì?

Q:

4. Các thư mục

>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
4 và
>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
5 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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
61 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

import os.path
folder = os.path.join( parent_folder, "python stuff" )
63 và
import os.path
folder = os.path.join( parent_folder, "python stuff" )
91 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

if os.path.exists( file ):
    with open( file, "r"  ) as infile:
        data = infile.read()
16 sẽ xóa một từ khóa khỏi kệ. Sau đó thêm một đối số dòng lệnh
if os.path.exists( file ):
    with open( file, "r"  ) as infile:
        data = infile.read()
17 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
import os.path

# get the desktop location ( since this is a special folder )
desktop = os.path.join(( os.environ["userprofile"] ), "desktop" )
file = os.path.join( desktop, "python stuff", "data.txt" )
if os.path.exists( file ):
    with open( file, "r" ) as infile:
        data = infile.read()
4

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
import os.path

# get the desktop location ( since this is a special folder )
desktop = os.path.join(( os.environ["userprofile"] ), "desktop" )
file = os.path.join( desktop, "python stuff", "data.txt" )
if os.path.exists( file ):
    with open( file, "r" ) as infile:
        data = infile.read()
5

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

import os
import os.path

# get the desktop location ( since this is a special folder )
desktop = os.path.join(( os.environ["userprofile"] ), "desktop" )
file = os.path.join( desktop, "python stuff", "data.txt" )
if os.path.exists( file ):
    with open( file, "r" ) as infile:
        data = infile.read()
6

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 thế nào để Python tìm thấy một tập tin?

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

Các tập tin python của tôi ở đâu?

Vị trí được cài đặt PY là C: \ Windows \ py.exe Nếu được cài đặt cho tất cả người dùng, nếu không có thể tìm thấy tại C: \ Users \ Username \ AppData \ Local \ Programs \ Python \ Launcher.C:\Windows\py.exe if installed for all users, otherwise can be found at C:\Users\username\AppData\Local\Programs\Python\Launcher .