Python 打印文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35702996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:50:22  来源:igfitidea点击:

Printing File Names

pythonpython-3.x

提问by Michael Mormon

I am very new to pythonand just installed Eric6I am wanting to search a folder (and all sub dirs) to print the filename of any file that has the extension of .pdfI have this as my syntax, but it errors saying

我是新来的python,刚刚安装Eric6我想搜索一个文件夹(和所有子目录)来打印任何具有扩展名的文件的文件名.pdf我把这个作为我的语法,但它错误说

The debugged program raised the exception unhandled FileNotFoundError
"[WinError 3] The system can not find the path specified 'C:'"
File: C:\Users\pcuser\EricDocs\Test.py, Line: 6

被调试的程序引发异常 unhandled FileNotFoundError
"[WinError 3] The system can not find the path specified 'C:'"
File: C:\Users\pcuser\EricDocs\Test.py, Line: 6

And this is the syntax I want to execute:

这是我要执行的语法:

import os

results = []
testdir = "C:\Test"
for folder in testdir:
  for f in os.listdir(folder):
    if f.endswith('.pdf'):
        results.append(f)

print (results)

回答by Inbar Rose

Use the globmodule.

使用glob模块。

The glob module finds all the pathnames matching a specified pattern

glob 模块查找与指定模式匹配的所有路径名

import glob, os
parent_dir = 'path/to/dir'
for pdf_file in glob.glob(os.path.join(parent_dir, '*.pdf')):
    print (pdf_file)

This will work on Windows and *nix platforms.

这将适用于 Windows 和 *nix 平台。



Just make sure that your path is fully escaped on windows, could be useful to use a raw string.

只要确保您的路径在 Windows 上完全转义,使用原始字符串可能很有用。

In your case, that would be:

在你的情况下,那将是:

import glob, os
parent_dir = r"C:\Test"
for pdf_file in glob.glob(os.path.join(parent_dir, '*.pdf')):
    print (pdf_file)


For only a list of filenames (not full paths, as per your comment) you can do this one-liner:

仅对于文件名列表(不是完整路径,根据您的评论),您可以执行以下单行操作:

results = [os.path.basename(f) for f in glob.glob(os.path.join(parent_dir, '*.pdf')]

回答by mattsap

Right now, you search each character string inside of testdir's variable.

现在,您搜索 testdir 变量中的每个字符串。

so it's searching the folder for values "C", ":", "\", "T" etc. You'll want to also escape your escape character like "C:\...\...\"

所以它在文件夹中搜索值“C”、“:”、“\”、“T”等。你还想转义你的转义字符,比如“C:\...\...\”

You probably was to use os.listdir(testdir) instead.

您可能要使用 os.listdir(testdir) 来代替。

回答by Sean Francis N. Ballais

Try running your Python script from C:. From the Command Prompt, you might wanna do this:

尝试从C:. 在命令提示符下,您可能想要这样做:

> cd C:\    
> python C:\Users\pcuser\EricDocs\Test.py

As pointed out by Tony Babarino, use r"C:\Test"instead of "C:\Test"in your code.

正如 Tony Babarino 所指出的r"C:\Test""C:\Test"在你的代码中使用而不是。

回答by Gareth Webber

There are a few problems in your code, take a look at how I've modified it below:

您的代码中存在一些问题,请查看我在下面如何修改它:

import os

results = []
testdir = "C:\Test"
for f in os.listdir(testdir):
    if f.endswith('.pdf'):
        results.append(f)

print (results)

Note that I have escaped your path name, and removed your first if folder.... That wasn't getting the folders as you expected, but rather selecting a character of the path string one at a time.

请注意,我已经转义了您的路径名,并删除了您的第一个if folder.... 这并没有像您预期的那样获取文件夹,而是一次选择一个路径字符串的一个字符。

You will need to modify the code to get it to look through all folders, this currently doesn't. Take a look at the globmodule.

您需要修改代码才能查看所有文件夹,目前还没有。看看glob模块。

回答by BChow

You will need to escape the backslash on windows and you can use os.walk to get all the pdf files.

您需要在 Windows 上转义反斜杠,您可以使用 os.walk 获取所有 pdf 文件。

   for root,dirs,files in os.walk(testdir):
       for f in files:
           if f.endswith('.pdf'):
            results.append(f)
   print (results)

回答by Iron Fist

You are basically iterating through the string testdirwith the first forloop then passing each character to os.listdir(folder)does not make any sense then, just remove that first forloop and use fnmatchmethod from fnmatchmodule:

您基本上是testdir用第一个for循环遍历字符串,然后将每个字符传递给os.listdir(folder)没有任何意义,只需删除第一个for循环并使用模块中的fnmatch方法fnmatch

import os
from fnmatch import fnmatch

ext = '*.pdf'
results = []
testdir = "C:\Test"
for f in os.listdir(testdir):
    if fnmatch(f, ext):
        results.append(f)

print (results)

回答by Tony Babarino

Try testdir = r"C:\Test"instead of testdir = "C:\Test". In python You have to escape special characters like for example \. You can escape them also with symbol '\' so it would be "C:\\Test". By using r"C:\Test", You are telling python to use rawstring.

尝试testdir = r"C:\Test"代替testdir = "C:\Test". 在 python 中,您必须转义特殊字符,例如\. 你也可以用符号 '\' 转义它们,所以它会是"C:\\Test". 通过使用r"C:\Test",您是在告诉 python 使用原始字符串。

Also for folder in testdir:line doesn't make sense because testdiris a string so You are basically trying to iterate over a string.

同样for folder in testdir:line 没有意义,因为它testdir是一个字符串,所以您基本上是在尝试遍历一个字符串。

回答by Imran

I had to mention the names of training images for my Yolomodel,
Here's what i did to print names of all images which i kept for training YoloV3Model

我不得不提到我的Yolo模型的训练图像的名称,
这是我为打印我为训练YoloV3模型保留的所有图像的名称所做的工作

import os

for root, dirs, files in os.walk("."):
    for filename in files:
        print(filename)

It prints out all the file names from the within the directory

它打印出目录中的所有文件名