Printing file names from a certain directory?

huangapple go评论66阅读模式
英文:

Printing file names from a certain directory?

问题

我正在尝试打印目录中所有文件的名称,格式如下:

```python
#文件名
file1
file2
file3
等等

文件结构如下:

文件夹
  主文件
  文件夹2
    其他文件

我尝试了以下代码,但它会打印额外的内容,而且每个文件之间没有换行:

print([entry.name for entry in os.scandir('formulas') if entry.is_file()])

我想使用“主文件”的代码来打印“其他文件”的名称。

抱歉如果格式有点奇怪,我对这不太熟悉。
我对Python也相对陌生,所以如果这是一个非常简单的修复方法,我很抱歉。

(问题已解决)
感谢atru


<details>
<summary>英文:</summary>

i&#39;m tryng to print the names of all the files in a directory with it looking something like this

#the file names
file1
file2
file3
ect

The file structure is like this

folder
mainfile
folder2
otherfiles



`print([entry for entry in os.scandir(&#39;formulas&#39;) if entry.is_file()])` ive tried this but it prints extra stuff and it doesnt skip a line per file

I want to print the names of &#39;otherfiles&#39; using code from &#39;mainfile&#39;
Sorry if this is weirdly formatted, im new to this.
I&#39;m also pretty new to python so sorry if this is a super easy fix

(solved)
thanks atru

</details>


# 答案1
**得分**: 0

[`os.scandir`](https://docs.python.org/3/library/os.html) 返回 [`os.DirEntry`](https://docs.python.org/3/library/os.html#os.DirEntry) 类的对象。这是您在代码中进行迭代和打印的内容。

要仅获取文件名,请调用 `os.DirEntry` 的 `.name` 成员:

```python
import os

for entry in os.scandir('.'):
    if entry.is_file():
        print(entry.name)
    else:
        continue

我稍微重新排列了您的代码 - 列表推导式很棒,但对于这样的任务,我个人更倾向于使用循环。现在您循环遍历 os.scandir() 返回的所有条目,仅打印文件。如果条目不是文件,代码将继续处理下一个对象。这里不需要 else 部分,但如果您计划在 if 之后执行其他操作,将需要它。我查看的是当前目录(即 '.'),您应根据需要更改它。

最后,在您的代码中,您构建了一个列表 - 然后将该列表作为整体打印出来,没有任何额外的格式化。这就是为什么您没有在新行上获取文件名的原因。在这里,您只需单独打印每个名称,并由Python添加新行。

这样说,一个更简化的版本如下:

import os

file_names = [entry.name for entry in os.scandir('.') if entry.is_file()]
print('\n'.join(file_names))

在这里,列表被打印为使用换行符作为分隔符创建的字符串。

英文:

os.scandir returns objects of class os.DirEntry. This is what you were iterating through in your code and what you were printing.

You can get only the file name by calling .name member of os.DirEntry,

import os

for entry in os.scandir(&#39;.&#39;):
    if entry.is_file():
        print(entry.name)
    else:
        continue

I rearranged your code a little - list comprehensions are great, but for a task like this I would personally go with a loop. Now you loop through all the entries returned to you by os.scandir() and print only ones that are files. If an entry is not a file, the code moves on to the next object. The else part is not needed here, but will be if you plan to do something after the if. I was looking at the current directory (i.e. '.'), you should change it accordingly.

Finally, in your code you were constructing a list - and then you were printing that list as a whole without any additional formatting. That's why you weren't getting your file names on new lines. Here you simply print each name separately, with a newline added by Python.

This said, a more minimal version would be as follows:

import os

file_names = [entry.name for entry in os.scandir(&#39;.&#39;) if entry.is_file()]
print(&#39;\n&#39;.join(file_names))

Here the list is printed as a string created using join with newline as a delimiter.

huangapple
  • 本文由 发表于 2023年5月29日 19:11:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76356836.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定