日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

目录指南中的Python列表文件-listdir VS system(“ ls”)通过示例进行解释

發(fā)布時(shí)間:2023/11/29 python 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 目录指南中的Python列表文件-listdir VS system(“ ls”)通过示例进行解释 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

🔹歡迎 (🔹 Welcome)

If you want to learn how these functions work behind the scenes and how you can use their full power, then this article is for you.

如果您想了解這些功能在后臺(tái)如何工作以及如何充分利用它們的功能,那么本文適合您。

We will start by diving into concepts that are essential to work with listdir and system:

我們將首先探討對(duì)于使用listdir和system必不可少的概念:

  • The built-in Python os module and how to import it.

    內(nèi)置的Python os模塊以及如何導(dǎo)入它。

  • The concepts of "directory" and "current working directory".

    “目錄”和“當(dāng)前工作目錄”的概念。
  • How to check and change your current working directory.

    如何檢查和更改您當(dāng)前的工作目錄。
  • The difference between an absolute path and a relative path.

    絕對(duì)路徑和相對(duì)路徑之間的差異。

Then, we will dive into the functions themselves:

然后,我們將深入研究這些函數(shù):

  • How to work with the listdir function and when to use it.

    如何使用listdir函數(shù)以及何時(shí)使用它。

  • How to work with the system("ls") function and when to use it.

    如何使用system("ls")函數(shù)以及何時(shí)使用它。

  • Examples of both of them and how they work behind the scenes.

    兩者的示例以及它們?cè)诤笈_(tái)的工作方式。

Let's begin! ?

讓我們開始! ?

OS操作系統(tǒng)模塊 (🔸 The OS Module)

The two functions that we will discuss: listdir() and system() belong to the os module. This module includes functions that are used to interact with your operating system, performing actions like:

我們將討論的兩個(gè)函數(shù): listdir()和system()屬于os模塊。 該模塊包括用于與操作系統(tǒng)交互的功能,它們執(zhí)行以下操作:

  • Making a new directory.

    制作一個(gè)新目錄。
  • Renaming an existing directory.

    重命名現(xiàn)有目錄。
  • Removing a directory.

    刪除目錄。
  • Displaying the path to your current working directory.

    顯示當(dāng)前工作目錄的路徑。
  • Much more!

    多得多!

💡 Tips:

💡 提示:

  • A directory is what we commonly know as a "folder", where we usually store related files and/or other directories, creating a hierarchy of directories within directories that are called subdirectories. An example of a directory is your "Documents" folder.

    目錄是我們通常所說的“文件夾”,我們通常在其中存儲(chǔ)相關(guān)文件和/或其他目錄,從而在稱為子目錄的目錄內(nèi)創(chuàng)建目錄的層次結(jié)構(gòu)。 目錄的一個(gè)示例是“文檔”文件夾。

  • A module is a file that contains related Python code.

    模塊是包含相關(guān)Python代碼的文件。

如何導(dǎo)入操作系統(tǒng)模塊 (How to Import the OS Module)

To use the os module in your script, you need to "import" it. Importing a module means gaining access to all the functions and variables that are stored within the module. We import a module when we want to use its code in our script.

要在腳本中使用os模塊,您需要“導(dǎo)入”它。 導(dǎo)入模塊意味著可以訪問模塊中存儲(chǔ)的所有功能和變量。 當(dāng)我們想在腳本中使用其代碼時(shí),我們將導(dǎo)入一個(gè)模塊。

To import the os module, you simply need to include this line at the top of your Python script or run this line in the interactive shell:

要導(dǎo)入os模塊,您只需要在Python腳本的頂部包含以下行或在交互式shell中運(yùn)行此行:

import os

This will give you access to all the functions defined in the os module.

這將使您可以訪問os模塊中定義的所有功能。

💡 Tip: this module was already installed when you installed Python 3, so you will be able to use it immediately.

💡 提示:安裝Python 3時(shí)已經(jīng)安裝了此模塊,因此您可以立即使用它。

To be able to use the functions from the os module, you will need to add the prefix os. before the name of the function that you want to call, like this:

為了能夠使用os模塊中的功能,您將需要添加前綴os. 要調(diào)用的函數(shù)名稱之前,如下所示:

os.<function>(<params>)

For example:

例如:

os.mkdir("New Folder")

如何導(dǎo)入單個(gè)功能 (How to Import Individual Functions)

If you are only going to work with one or two functions from the module, you can import them individually using this syntax:

如果只打算使用模塊中的一個(gè)或兩個(gè)功能,則可以使用以下語法分別導(dǎo)入它們:

from <module> import <function1>, <function2>, ...

For example:

例如:

from os import listdir, system

In this case, you can call the functions in your script as you normally would, without adding the os. prefix, like this:

在這種情況下,您可以像往常一樣在腳本中調(diào)用函數(shù), 而無需添加os. 前綴,像這樣:

<function>(<params>)

For example:

例如:

mkdir("New Folder")

🔹當(dāng)前工作目錄 (🔹 Current Working Directory)

Now let's see a very important concept that you need to know before you start working with listdir and system. Your current working directory, as the name implies, is the directory (folder) where you are currently working.

現(xiàn)在,讓我們看看在開始使用listdir和system之前需要了解的一個(gè)非常重要的概念。 顧名思義,您當(dāng)前的工作目錄就是您當(dāng)前工作的目錄(文件夾)。

You can check your current working directory with this function from the os module:

您可以從os模塊中使用此功能檢查當(dāng)前的工作目錄:

os.getcwd()

This will show you the path to your current working directory.

這將向您顯示當(dāng)前工作目錄的路徑。

💡 Tip: cwd means "current working directory."

💡 提示: cwd意思是“當(dāng)前工作目錄”。

從交互式外殼 (From the Interactive Shell)

If I run this command in the interactive shell (Windows), I see this:

如果在交互式外殼程序(Windows)中運(yùn)行此命令,則會(huì)看到以下信息:

>>> os.getcwd() 'C:\\Users\\estef\\AppData\\Local\\Programs\\Python\\Python38-32'

This is the full path to my current working directory:

這是我當(dāng)前工作目錄的完整路徑:

'C:\\Users\\estef\\AppData\\Local\\Programs\\Python\\Python38-32'

從腳本 (From a Script)

If I run this command from a script, like this:

如果我從腳本運(yùn)行此命令,如下所示:

import os print(os.getcwd())

I see:

我懂了:

C:\Users\estef\Documents\freeCodeCamp\freeCodeCamp News\listdir vs system

The full path to the script (its location in the system, in the hierarchy of directories).

腳本的完整路徑(其在系統(tǒng)中的位置,在目錄層次結(jié)構(gòu)中)。

💡 Tip: If you run a script (a Python file), your current working directory is the directory where the script is currently in.

💡 提示:如果運(yùn)行腳本(Python文件),則當(dāng)前的工作目錄是腳本當(dāng)前所在的目錄。

如何更改當(dāng)前工作目錄 (How to Change your Current Working Directory)

You can change your current working directory with this command from the os module:

您可以通過os模塊中的以下命令更改當(dāng)前工作目錄:

os.chdir(<path>)

You will need to specify the path to the new working directory, passing it as an argument, formatted as a string. It can be either an absolute path or a relative path.

您將需要指定新工作目錄的路徑,并將其作為參數(shù)傳遞,格式為字符串。 它可以是絕對(duì)路徑,也可以是相對(duì)路徑。

💡 Tip:

💡 提示:

  • An absolute path specifies all the sequence of directories that you need to go through to reach your target directory. This path starts from the root directory of your system.

    絕對(duì)路徑指定到達(dá)目標(biāo)目錄所需的所有目錄順序。 此路徑從系統(tǒng)的根目錄開始。

For example:

例如:

>>> import os >>> os.chdir(r"C:\Users\estef\Documents\FreeCodeCamp\freeCodeCamp News\9 - listdir vs system")# Checking current working directory: >>> os.getcwd() 'C:\\Users\\estef\\Documents\\FreeCodeCamp\\freeCodeCamp News\\9 - listdir vs system'

Notice that I added an r before the absolute path to convert the string into a raw string. If you use \ and you don't add the r, you will get an error because the \ symbol will be treated as a special character.

請(qǐng)注意,我在絕對(duì)路徑之前添加了r ,以將字符串轉(zhuǎn)換為原始字符串。 如果您使用\而未添加r ,則會(huì)出現(xiàn)錯(cuò)誤,因?yàn)閈符號(hào)將被視為特殊字符。

Alternatively, you could replace the backslashes ?\ with forward slashes / in the path:

或者,您可以在路徑中將反斜杠\替換為正斜杠/ :

>>> os.chdir("C:/Users/estef/Documents/FreeCodeCamp/freeCodeCamp News/9 - listdir vs system")# Checking current working directory >>> os.getcwd() 'C:\\Users\\estef\\Documents\\FreeCodeCamp\\freeCodeCamp News\\9 - listdir vs system'
  • A relative path specifies the path that you want to follow to find the target directory, but now the path starts from your current working directory. It's shorter and simpler than the absolute path.

    相對(duì)路徑指定了要查找目標(biāo)目錄所要遵循的路徑,但是現(xiàn)在該路徑從當(dāng)前工作目錄開始。 它比絕對(duì)路徑更短,更簡單。

For example, if your current working directory contains a subdirectory (folder) Directory 1, you can move to this directory using a relative path (imagine it as a folder within another folder, and we are going deeper and deeper into the hierarchy), like this:

例如,如果您當(dāng)前的工作目錄包含一個(gè)子目錄(文件夾) Directory 1 ,則可以使用相對(duì)路徑(將其想象為另一個(gè)文件夾中的一個(gè)文件夾,并將其深入層次結(jié)構(gòu))移至該目錄。這個(gè):

>>> import os >>> os.chdir(".\Directory 1")# Check current working directory >>> os.getcwd() 'C:\\Users\\estef\\Documents\\FreeCodeCamp\\freeCodeCamp News\\9 - listdir vs system\\Directory 1'

💡 Tip: The dot (.) at the beginning of the relative path .\Directory 1 represents the current working directory. A double dot ( ..) is used to move up the hierarchy, to the "parent" directory.

💡 提示:相對(duì)路徑.\Directory 1開頭的點(diǎn)( . )表示當(dāng)前工作目錄。 雙點(diǎn)( .. )用于將層次結(jié)構(gòu)向上移動(dòng)到“父”目錄。

Now that you have all the background knowledge that you will need to truly understand how listdir and system work, let's see them in detail.

現(xiàn)在,您已經(jīng)具備了真正了解listdir和system如何工作所需的所有背景知識(shí),下面讓我們對(duì)其進(jìn)行詳細(xì)介紹。

🔸Listdir (🔸 Listdir)

We will start with the listdir function. Let's reveal its mysteries. 🔮

我們將從listdir函數(shù)開始。 讓我們揭示它的奧秘。 🔮

目的和返回值 (Purpose and Return Value)

According to the Python Documentation, the purpose of this function is to:

根據(jù)Python文檔 ,此功能的目的是:

Return a list containing the names of the entries in the directory given by path.

返回包含path指定的目錄中條目名稱的列表。

Basically, this function returns a list with the names of all files and directories that are currently found within a particular directory that you specify when you call the function.

基本上,此函數(shù)返回一個(gè)列表,其中包含在調(diào)用該函數(shù)時(shí)指定的特定目錄中當(dāng)前找到的所有文件和目錄的名稱。

💡 Tip: The list will not have a specific order, even if you usually sort the elements alphabetically.

💡 提示:即使您通常按字母順序?qū)υ剡M(jìn)行排序,列表也沒有特定的順序。

語法和參數(shù) (Syntax and Parameter)

To call listdir, will need to use this syntax:

調(diào)用listdir ,將需要使用以下語法:

The parameter path is precisely that, the absolute or relative path to the directory that you want to visualize. In Python 3.2 and above, this parameter is optional. By default, the path will lead to your current working directory if you don't pass an argument.

參數(shù)path正是要顯示的目錄的絕對(duì)或相對(duì)路徑。 在Python 3.2及更高版本中,此參數(shù)是可選的。 默認(rèn)情況下,如果不傳遞參數(shù),該路徑將導(dǎo)致當(dāng)前工作目錄。

Remember that you must import the os module before calling this function.

請(qǐng)記住,在調(diào)用此函數(shù)之前,必須導(dǎo)入os模塊。

💡 Tip: If you use this import statement from os import listdir to import the function individually, you can omit the os. prefix, like this:

提示:如果您使用from os import listdir import語句單獨(dú)導(dǎo)入函數(shù),則可以省略os. 前綴,像這樣:

用例和優(yōu)勢(shì) (Use Cases and Advantages)

The function listdir is very helpful because it works on any operating system where Python runs, so if Python is installed on your device, this function will work correctly.

listdir函數(shù)非常有用,因?yàn)樗稍谶\(yùn)行Python的任何操作系統(tǒng)上運(yùn)行,因此,如果您的設(shè)備上安裝了Python,則此函數(shù)將正常運(yùn)行。

Now let's talk a little bit about its return value. Since it returns a list, we can store this list in a variable and work with it in our program.

現(xiàn)在讓我們談?wù)勊姆祷刂怠?由于它返回一個(gè)列表,因此我們可以將該列表存儲(chǔ)在變量中并在程序中使用它。

For example, let's say that we want to do something with all the files from a given directory, such as converting images to black and white or modifying their content. We could do it using a for loop, like this:

例如,假設(shè)我們要處理給定目錄中的所有文件,例如將圖像轉(zhuǎn)換為黑白或修改其內(nèi)容。 我們可以使用for循環(huán)來做到這一點(diǎn),就像這樣:

images = os.listdir(<path>)for image in images:# Do something to the image

Of course, you would need to define what happens within the loop, but this is an example of what you could do with this function.

當(dāng)然,您需要定義循環(huán)中發(fā)生的事情,但這是您可以使用此函數(shù)進(jìn)行操作的一個(gè)示例。

This is awesome, right?

太棒了吧?

But having files and directories in the same list can be a little bit problematic if we want to work with a for loop, right? We would need to add a conditional to check the type of each element. How can we make a list that only contains file names (no directories) or vice versa?

但是,如果我們要使用for循環(huán),將文件和目錄放在同一列表中可能會(huì)有些問題,對(duì)吧? 我們需要添加一個(gè)條件來檢查每個(gè)元素的類型。 我們?nèi)绾沃谱鲀H包含文件名(無目錄)的列表,反之亦然?

Let's see! ?

讓我們來看看! ?

僅包含文件 (Only Include Files)

If you want to "filter" the list returned by os.listdir() to include only files (no directories) you can use this line of code:

如果要“過濾” os.listdir()返回的列表以僅包含文件 (不包含目錄),則可以使用以下代碼行:

list(filter(os.path.isfile, os.listdir(<path>)))

💡 Tip: You can customize the <path> argument or omit it to use your current working directory.

💡 提示:您可以自定義<path>參數(shù)或忽略它以使用當(dāng)前工作目錄。

Let's see an example with my current working directory (I'm using Windows):

讓我們來看一個(gè)當(dāng)前工作目錄的示例(我正在使用Windows):

My directory (folder) has:

我的目錄(文件夾)有:

  • Two subdirectories (folders within the main folder)

    兩個(gè)子目錄(主文件夾中的文件夾)
  • One PowerPoint file

    一個(gè)PowerPoint文件
  • One image (.png file)

    一幅圖片(.png文件)
  • One Python script

    一個(gè)Python腳本

If I call the listdir function from the script.py file and print the list returned:

如果我從script.py文件調(diào)用listdir函數(shù)并打印返回的列表:

print(os.listdir())

This is the output:

這是輸出:

['Diagrams.ppt', 'Directory 1', 'Directory 2', 'listdir vs system.png', 'script.py']

You can see that all files and directories from my current working directory were included.

您可以看到包含了當(dāng)前工作目錄中的所有文件和目錄。

To filter the list to only contain files, we can use this statement:

要過濾列表以僅包含文件,我們可以使用以下語句:

print(list(filter(os.path.isfile, os.listdir())))

Now the output is:

現(xiàn)在的輸出是:

['Diagrams.ppt', 'listdir vs system.png', 'script.py']

Notice how the directories were "filtered", exactly what we wanted.

注意目錄是如何被“過濾”的,正是我們想要的。

僅包括目錄 (Only Include Directories)

Similarly, if you want to "filter" the list to include only directories, you can use this line of code:

同樣,如果您要“過濾”列表以僅包含目錄 ,則可以使用以下代碼行:

list(filter(os.path.isdir, os.listdir(<path>)))

Now the output is:

現(xiàn)在的輸出是:

['Directory 1', 'Directory 2']

Exactly what we wanted. But how does this statement work behind the scenes? Let's see.

正是我們想要的。 但是,這種說法在幕后如何運(yùn)作? 讓我們來看看。

filter()在幕后的工作方式 (How filter() Works Behind the Scenes)

The filter function is called using this syntax:

使用以下語法調(diào)用filter函數(shù):

filter(<function>, <list>)

It basically "filters" the elements of the second argument (the list) based on the truth value returned by calling the function passed as the first argument (os.path.isfile() or os.path.isdir() in their respective commands):

基本上,它基于通過調(diào)用作為第一個(gè)參數(shù)傳遞的函數(shù)( os.path.isfile()或os.path.isdir()在各自的命令中os.path.isdir()返回的真值而“過濾”第二個(gè)參數(shù)(列表)的元素。 ):

print(list(filter(os.path.isfile, os.listdir())))list(filter(os.path.isdir, os.listdir()))

These two functions:

這兩個(gè)功能:

os.path.isfile(<path>)os.path.isdir(<path>)

Return True if the argument is a file or a directory, respectively. ?

如果參數(shù)分別是文件或目錄,則返回True 。

Based on these truth values, the elements of the list will be included (or not) in the final "filtered" list. The elements of the list returned by os.listdir() are passed one by one to these functions to check if they are files (or directories, respectively).

基于這些真值,列表的元素將包含(或不包含)在最終的“過濾”列表中。 os.listdir()返回的列表元素將一一傳遞給這些函數(shù),以檢查它們是否分別是文件(或目錄)。

For example: If we have this line of code:

例如:如果我們有以下代碼行:

filter(os.path.isfile, os.listdir())))

And os.listdir() returns this list:

os.listdir()返回以下列表:

['Diagrams.ppt', 'Directory 1', 'Directory 2', 'script.py']

The first element of the list ('Diagrams.ppt') is passed as argument to os.path.isfile() to check if it's a file :

列表的第一個(gè)元素( 'Diagrams.ppt' )作為參數(shù)傳遞給os.path.isfile()以檢查它是否為文件:

os.path.isfile('Diagrams.ppt') # True

The function call returns True, so it's a file and it's included in the list.

該函數(shù)調(diào)用返回True ,因此它是一個(gè)文件,并且包含在列表中。

But if the element is a directory:

但是,如果元素是目錄:

os.path.isfile('Directory 1') # False

The function call returns False, so it's not included in the list. This process continues for every element in the list until the new list only contains file names.

該函數(shù)調(diào)用返回False ,因此它不包含在列表中。 對(duì)于列表中的每個(gè)元素,此過程將繼續(xù)進(jìn)行,直到新列表僅包含文件名為止。

Then, since filter() returns an iterable, we make a list from this iterable using list():

然后,由于filter()返回一個(gè)可迭代對(duì)象,因此我們使用list()從該可迭代對(duì)象中創(chuàng)建一個(gè)列表:

list(filter(os.path.isfile, os.listdir()))

And we print it since we are working with a Python file (script):

由于我們正在使用Python文件(腳本),因此我們將其打印出來:

print(list(filter(os.path.isfile, os.listdir())))

💡 Tip: You can visually identify if an element of the list represents a file or a directory by seeing if it has an extension (type) after its name. For example: Diagrams.ppt has a .ppt extension that tells you that it's a PowerPoint file but a directory doesn't have an extension, like 'Directory 1'.

提示:您可以通過查看列表中元素的名稱后是否具有擴(kuò)展名(類型)來直觀地識(shí)別列表中的元素代表文件還是目錄。 例如: Diagrams.ppt具有.ppt擴(kuò)展名,它告訴您它是PowerPoint文件,但目錄沒有擴(kuò)展名,如'Directory 1' 。

🔹系統(tǒng)(“ ls”) (🔹 System("ls"))

Now that you know how to work with listdir, let's see how the system() function works behind the scenes and how you can use it. 🔮

現(xiàn)在,您知道如何使用listdir ,讓我們看看system()函數(shù)如何在后臺(tái)工作以及如何使用它。 🔮

目的 (Purpose )

According to the Python Documentation, the purpose of the system() function is to:

根據(jù)Python文檔 , system()函數(shù)的目的是:

Execute the command (a string) in a subshell在子shell中執(zhí)行命令(字符串)

Basically, this function takes a command (as a string) and executes it.

基本上,此函數(shù)接受命令(作為字符串)并執(zhí)行它。

In this case, the command that we are passing is 'ls' , a Unix command used in Linux to display the content of a directory as standard output.

在這種情況下,我們傳遞的命令是'ls' ,這是Linux中使用的Unix命令,用于將目錄的內(nèi)容顯示為標(biāo)準(zhǔn)輸出。

Unlike listdir, the system() function will not return a list if we pass the 'ls' command, it will only display the list of files and directories as standard output. Therefore, you should use it if you only want to visualize the list without actually working with it in your program.

與listdir不同,如果我們通過'ls'命令, system()函數(shù)將不會(huì)返回列表 ,它只會(huì)將文件和目錄的列表顯示為標(biāo)準(zhǔn)輸出。 因此,如果您只想可視化列表而不在程序中實(shí)際使用它,則應(yīng)使用它。

語法和參數(shù) (Syntax and Parameter)

To call this function, you will need to use this syntax:

要調(diào)用此函數(shù),您將需要使用以下語法:

Its only argument is the command that you want to execute formatted as a string (surrounded by double quotes or single quotes).

它唯一的參數(shù)是要執(zhí)行的命令,格式為字符串(用雙引號(hào)或單引號(hào)引起來)。

Particularly, the ls command lets you see the content of your current working directory.

特別是,通過ls命令,您可以查看當(dāng)前工作目錄的內(nèi)容。

For example: if this is my working directory (three Python files and one subdirectory):

例如:如果這是我的工作目錄(三個(gè)Python文件和一個(gè)子目錄):

And I call the system() function, like this:

然后調(diào)用system()函數(shù),如下所示:

>>> import os >>> os.system("ls")

This is the output:

這是輸出:

'Directory 1' 'file 1.py' 'file 2.py' main.py 0

We can see the standard output in the console (the list of files and directories):

我們可以在控制臺(tái)中看到標(biāo)準(zhǔn)輸出(文件和目錄的列表):

'Directory 1' 'file 1.py' 'file 2.py' main.py

and the return value:

和返回值:

0

💡 Note: For these examples of the system() function, I'm working with an online command line tool called Repl.it since my computer has Windows installed and the command ls is not recognized by the default command prompt.

💡 注意:對(duì)于這些system()函數(shù)的示例,由于我的計(jì)算機(jī)已安裝Windows,并且默認(rèn)命令提示符無法識(shí)別ls命令,因此我正在使用名為Repl.it的在線命令行工具。

局限性 (Limitations)

One of the main limitation of this function is that the command passed as argument has to be recognized by the operating system or environment that you are working with.

此功能的主要限制之一是作為參數(shù)傳遞的命令必須由您使用的操作系統(tǒng)或環(huán)境識(shí)別。

For example, the ls command will not be recognized in Windows by default in the command prompt. You will see this error if you try to run it:

例如,默認(rèn)情況下,在命令提示符下,Windows無法識(shí)別ls命令。 如果嘗試運(yùn)行它,將會(huì)看到此錯(cuò)誤:

'ls' is not recognized as an internal or external command, operable program or batch file.無法將“ ls”識(shí)別為內(nèi)部或外部命令,可操作程序或批處理文件。

A similar command in Windows would be the 'dir' command:

Windows中類似的命令是'dir'命令:

os.system('dir')

💡 Tip: There are alternative ways to run the ls command on Windows, such as using terminal programs that recognize Unix commands, but by default Windows does not recognize the 'ls' command.

💡提示:還有其他方法可以在Windows上運(yùn)行l(wèi)s命令,例如使用識(shí)別Unix命令的終端程序,但是默認(rèn)情況下Windows無法識(shí)別'ls'命令。

返回值 (Return Value)

According to the Python documentation:

根據(jù)Python文檔 :

On Unix, the return value is the exit status of the process encoded in the format specified for wait().

在Unix上,返回值是以為wait()指定的格式編碼的進(jìn)程的退出狀態(tài)。

and...

和...

On Windows, the return value is that returned by the system shell after running command.

在Windows上,返回值是在運(yùn)行command之后由系統(tǒng)外殼返回的值。

💡 ?Tip: Note that this function does not return a list. It simply displays the list as standard output, so you can't store it in a variable like you did with listdir.

💡 提示:請(qǐng)注意,此功能不會(huì)返回列表。 它只是將列表顯示為標(biāo)準(zhǔn)輸出,因此您不能像使用listdir一樣將其存儲(chǔ)在變量中。

ls命令的變體 (Variations of the ls command)

A key feature of os.system('ls') is that it has many helpful and interesting options to customize how present the output. Let's see some of them.

os.system('ls')的關(guān)鍵功能是它具有許多有用且有趣的選項(xiàng),可自定義輸出的顯示方式。 讓我們來看一些。

Option 1: We can show more information about files and directories such as their size, location, and modification date and time using the command ls -l.

選項(xiàng)1:我們可以使用命令ls -l顯示有關(guān)文件和目錄的更多信息,例如文件和目錄的大小,位置以及修改日期和時(shí)間。

>>> import os >>> os.system('ls -l') total 12 drwxr-xr-x 1 runner runner 0 Apr 3 18:23 'Directory 1' -rw-r--r-- 1 runner runner 11 Apr 3 18:38 'file 1.py' -rw-r--r-- 1 runner runner 11 Apr 3 18:38 'file 2.py' -rw-r--r-- 1 runner runner 11 Apr 3 18:38 main.py 0

Option 2: To be able to visually recognize directories faster, we can use ls -F, which adds a forward slash / to the end of their names (see 'Directory 1/' below).

選項(xiàng)2:為了能夠在視覺上更快地識(shí)別目錄,我們可以使用ls -F ,在其名稱的末尾添加一個(gè)斜杠/ (請(qǐng)參見下面的'Directory 1/' )。

>>> import os >>> os.system('ls -F') 'Directory 1'/ 'file 1.py' 'file 2.py' main.py 0

Option 3: To sort the files by size, we can use the command ls -lS.

選項(xiàng)3:要按大小對(duì)文件排序,我們可以使用命令ls -lS 。

>>> import os >>> os.system('ls -lS') total 12 -rw-r--r-- 1 runner runner 11 Apr 3 18:38 'file 1.py' -rw-r--r-- 1 runner runner 11 Apr 3 18:38 'file 2.py' -rw-r--r-- 1 runner runner 11 Apr 3 18:38 main.py drwxr-xr-x 1 runner runner 0 Apr 3 18:23 'Directory 1' 0

There are many more options for customization that can be helpful for your particular goal. Here you can find more information about the -ls command and how you can use its full power.

還有許多自定義選項(xiàng)可以對(duì)您的特定目標(biāo)有所幫助。 在這里,您可以找到有關(guān)-ls命令以及如何使用其全部功能的更多信息 。

list listdir與system(“ ls”)的摘要 (🔸 Summary of listdir vs. system("ls"))

  • Purpose: listdir returns the list of file names and directories in the path specified (by default, the current working directory) while system("ls") only displays them as standard output.

    用途: listdir返回指定路徑(默認(rèn)情況下為當(dāng)前工作目錄)中文件名和目錄的列表,而system("ls")僅將它們顯示為標(biāo)準(zhǔn)輸出。

  • Operating System: listdir can be used independently of the operating system that you are working with. In contrast, system('ls') has to be executed in an operating system or environment that recognizes the 'ls' command.

    操作系統(tǒng): listdir可以獨(dú)立于所使用的操作系統(tǒng)使用。 相反,必須在可識(shí)別'ls'命令的操作系統(tǒng)或環(huán)境中執(zhí)行system('ls') 。

  • Customization: you can filter the list returned by listdir if you need to remove files or directories using the filter() function and you can pass options to customize the output of system('ls').

    自定義:如果需要使用filter()函數(shù)刪除文件或目錄,則可以過濾listdir返回的列表,并且可以傳遞選項(xiàng)以自定義system('ls')的輸出。

I really hope that you liked my article and found it helpful. Now you can work with these functions in your Python projects. Check out my online courses. Follow me on Twitter. 👍

我真的希望您喜歡我的文章并發(fā)現(xiàn)它對(duì)您有所幫助。 現(xiàn)在,您可以在Python項(xiàng)目中使用這些功能。 查看我的在線課程 。 在Twitter上關(guān)注我。 👍

翻譯自: https://www.freecodecamp.org/news/python-list-files-in-a-directory-guide-listdir-vs-system-ls-explained-with-examples/

總結(jié)

以上是生活随笔為你收集整理的目录指南中的Python列表文件-listdir VS system(“ ls”)通过示例进行解释的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。