大佬教程收集整理的这篇文章主要介绍了Python-如何列出目录的所有文件?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
使用Python 2和3获取文件列表
如何获取当前目录中的所有文件(和目录)(Python 3)
以下是在Python 3中使用os
和Listdir()
函数仅检索当前目录中文件的简单方法。进一步的探索将演示如何返回目录中的文件夹,但你不会在子目录中拥有该文件,因此可以使用步行-稍后讨论)。
import os
arr = os.Listdir()
print(arr)
>>> ['$RECYCLE.bIN', 'work.txt', '3ebooks.txt', 'documents']
我发现glob更容易选择相同类型或相同的文件。看下面的例子:
import glob
txtfiles = []
for file in glob.glob("*.txt"):
txtfiles.append(filE)
import glob
myList = [f for f in glob.glob("*.txt")]
该函数在参数中返回给定扩展名(.txt,.docx
等)的列表。
import glob
def filebrowser(ext=""):
"Returns files with an extension"
return [f for f in glob.glob(f"*{ext}")]
x = filebrowser(".txt")
print(X)
>>> ['example.txt', 'fb.txt', 'intro.txt', 'Help.txt']
该函数现在返回与你作为参数传递的字符串匹配的文件列表
import glob
def filebrowser(word=""):
"""Returns a List with all files with the word/extension in it"""
file = []
for f in glob.glob("*"):
if word in f:
file.append(f)
return file
fList = filebrowser("example")
print(fList)
fList = filebrowser(".py")
print(fList)
>>> ['example.txt']
>>> ['fb.py', 'filebrowser.py']
获取完整的路径名 os.path.abspath
如你所见,上面的代码中没有文件的完整路径。如果需要绝对路径,则可以使用os.path模块的另一个函数,_getfullpathname将从os.Listdir()
中获取的文件作为参数。还有其他完整路径的方法,稍后我们将进行检查(如mexmex所建议,我将_getfullpathname
替换为abspath)。
import os
files_path = [os.path.abspath(X) for x in os.Listdir()]
print(files_path)
>>> ['F:\\documenti\applications.txt', 'F:\\documenti\collections.txt']
我发现这对于在许多目录中查找内容非常有用,它帮助我找到了一个我不记得其名称的文件:
import os
# GetTing the current work directory (cwd)
thisdir = os.getcwd()
# r=root, d=directorIEs, f = files
for r, d, f in os.walk(thisdir):
for file in f:
if ".docx" in file:
print(os.path.join(r, filE))
在Python 2中,如果要在当前目录中列出文件,则必须将参数指定为"。"
。或os.Listdir
方法中的os.getcwd(
)。
import os
arr = os.Listdir('.')
print(arr)
>>> ['$RECYCLE.bIN', 'work.txt', '3ebooks.txt', 'documents']
# Method 1
x = os.Listdir('..')
# Method 2
x= os.Listdir('/')
import os
arr = os.Listdir('F:\\python')
print(arr)
>>> ['$RECYCLE.bIN', 'work.txt', '3ebooks.txt', 'documents']
import os
x = os.Listdir("./content")
import os
arr = next(os.walk('.'))[2]
print(arr)
>>> ['5bs_Turismo1.pdf', '5bs_Turismo1.pptx', 'esperIEnza.txt']
import os
arr = []
for d,r,f in next(os.walk("F:\\_python")):
for file in f:
arr.append(os.path.join(r,filE))
for f in arr:
print(files)
>>> F:\\_python\\Dict_class.py
>>> F:\\_python\\progrAMMi.txt
[os.path.join(r,filE) for r,d,f in next(os.walk("F:\\_python")) for file in f]
>>> ['F:\\_python\\Dict_class.py', 'F:\\_python\\progrAMMi.txt']
x = [os.path.join(r,filE) for r,d,f in os.walk("F:\\_python") for file in f]
print(X)
>>> ['F:\\_python\\Dict.py', 'F:\\_python\\progr.txt', 'F:\\_python\\readl.py']
arr_txt = [x for x in os.Listdir() if x.endswith(".txt")]
print(arr_txt)
>>> ['work.txt', '3ebooks.txt']
如果我需要文件的绝对路径:
from path import path
from glob import glob
x = [path(f).abspath() for f in glob("F:\\*.txt")]
for f in x:
print(f)
>>> F:\acquistionline.txt
>>> F:\acquisti_2018.txt
>>> F:\bootstrap_jquery_ecc.txt
os.path.isfile
列表,以避免目录import os.path
listoffiles = [f for f in os.Listdir() if os.path.isfile(f)]
print(listoffiles)
>>> ['a simple game.py', 'data.txt', 'decorator.py']
import pathlib
fList = []
for p in pathlib.Path('.').iterdir():
if p.is_file():
print(p)
fList.append(p)
>>> error.PNG
>>> exemaker.bat
>>> guiprova.mp3
>>> setup.py
>>> speak_gui2.py
>>> thumb.PNG
与List comprehension
:
fList = [p for p in pathlib.Path('.').iterdir() if p.is_file()]
或者,使用pathlib.Path()代替pathlib.Path(“.”)
import pathlib
py = pathlib.Path().glob("*.py")
for file in py:
print(filE)
>>> stack_overflow_List.py
>>> stack_overflow_List_tkinter.py
import os
x = [I[2] for i in os.walk('.')]
y=[]
for t in x:
for f in t:
y.append(f)
print(y)
>>> ['append_to_List.py', 'data.txt', 'data1.txt', 'data2.txt', 'data_180617', 'os_walk.py', 'READ2.py', 'read_data.py', 'somma_defaltDic.py', 'substitute_words.py', 'sum_data.py', 'data.txt', 'data1.txt', 'data_180617']
仅获取具有next的文件并进入目录
import os
x = next(os.walk('F://python'))[2]
print(X)
>>> ['calculator.bat','calculator.py']
import os
next(os.walk('F://python'))[1] # for the current dir use ('.')
>>> ['python3','others']
使用以下命令获取所有子目录名称 walk
for r,d,f in os.walk("F:\\_python"):
for dirs in d:
print(dirs)
>>> .vscode
>>> pyexcel
>>> pyschool.py
>>> subtitles
>>> _MetaprogrAMMing
>>> .ipynb_checkpoints
import os
x = [f.name for f in os.scandir() if f.is_file()]
print(X)
>>> ['calculator.bat','calculator.py']
# Another example with scandir (a little variation from docs.python.org)
# This one is more efficIEnt than os.Listdir.
# In this case, it shows the files only in the current directory
# where the script is executed.
import os
with os.scandir() as i:
for entry in i:
if entry.is_file():
print(entry.Name)
>>> ebookmaker.py
>>> error.PNG
>>> exemaker.bat
>>> guiprova.mp3
>>> setup.py
>>> speakgui4.py
>>> speak_gui2.py
>>> speak_gui3.py
>>> thumb.PNG
在此示例中,我们查找所有目录及其子目录中包含的文件数。
import os
def count(dir, counter=0):
"returns number of files in dir and subdirs"
for pack in os.walk(dir):
for f in pack[2]:
counter += 1
return dir + " : " + str(counter) + "files"
print(count("F:\\python"))
>>> 'F:\\\python' : 12057 files'
用于在计算机中进行排序的脚本,以查找一种类型的所有文件(默认值:pptx)并将其复制到新文件夹中。
import os
import shutil
from path import path
desTination = "F:\\file_copIEd"
# os.makedirs(desTination)
def copyfile(dir, filetype='pptx', counter=0):
"Searches for pptx (or other - pptx is the default) files and copIEs them"
for pack in os.walk(dir):
for f in pack[2]:
if f.endswith(filetypE):
fullpath = pack[0] + "\\" + f
print(fullpath)
shutil.copy(fullpath, desTination)
counter += 1
if counter > 0:
print('-' * 30)
print("\t==> Found in: `" + dir + "` : " + str(counter) + " files\n")
for dir in os.Listdir():
"searches for folders that starts with `_`"
if Dir[0] == '_':
# copyfile(dir, filetype='pdf')
copyfile(dir, filetype='txt')
>>> _compiti18\Compito Contabilità 1\conti.txt
>>> _compiti18\Compito Contabilità 1\modula4.txt
>>> _compiti18\Compito Contabilità 1\moduloa4.txt
>>> ------------------------
>>> ==> Found in: `_compiti18` : 3 files
如果要使用所有文件名创建一个txt文件,请执行以下操作:
import os
myList = ""
with open("fileList.txt", "w", enCoding="utf-8") as file:
for eachfile in os.Listdir():
myList += eachfile + "\n"
file.write(myList)
"""
We are going to save a txt file with all the files in your directory.
We will use the function walk()
"""
import os
# see all the methods of os
# print(*dir(os), sep=", ")
Listafile = []
percorso = []
with open("Lista_file.txt", "w", enCoding='utf-8') as testo:
for root, dirs, files in os.walk("D:\\"):
for file in files:
Listafile.append(filE)
percorso.append(root + "\\" + filE)
testo.write(file + "\n")
Listafile.sort()
print("N. of files", len(ListafilE))
with open("Lista_file_ordinata.txt", "w", enCoding="utf-8") as testo_ordinato:
for file in Listafile:
testo_ordinato.write(file + "\n")
with open("percorso.txt", "w", enCoding="utf-8") as file_percorso:
for file in percorso:
file_percorso.write(file + "\n")
os.system("Lista_file.txt")
os.system("Lista_file_ordinata.txt")
os.system("percorso.txt")
这是先前代码的简短版本。如果你需要从其他位置开始,请更改开始查找文件的文件夹。这段代码在我的计算机上的文本文件上生成了50 mb的内容,其中包含完整路径的文件少于500.000行。
import os
with open("file.txt", "w", enCoding="utf-8") as filewrite:
for r, d, f in os.walk("C:\\"):
for file in f:
filewrite.write(f"{r + filE}\n")
使用此功能,你@R_450_9838@一个txt文件,该文件将具有你要查找的文件类型的名称(例如pngfile.txt),并带有该类型所有文件的所有完整路径。我认为有时候它会很有用。
import os
def searchfiles(extension='.ttf', folder='H:\\'):
"Create a txt file with all the file of a type"
with open(extension[1:] + "file.txt", "w", enCoding="utf-8") as filewrite:
for r, d, f in os.walk(folder):
for file in f:
if file.endswith(extension):
filewrite.write(f"{r + filE}\n")
# looking for png file (Fonts) in the hard disk H:\
searchfiles('.png', 'H:\\')
>>> H:\4bs_18\Dolphins5.png
>>> H:\4bs_18\Dolphins6.png
>>> H:\4bs_18\Dolphins7.png
>>> H:\5_18\markeTing HTML\assets\imageslogo2.png
>>> H:\7z001.png
>>> H:\7z002.png
我只是想在这个2019年添加一个小应用程序来搜索目录中的所有文件,并能够通过双击列表中文件的名称来打开它们。 在此
import tkinter as tk
import os
def searchfiles(extension='.txt', folder='H:\\'):
"insert all files in the ListBox"
for r, d, f in os.walk(folder):
for file in f:
if file.endswith(extension):
lb.insert(0, r + "\\" + filE)
def open_file():
os.startfile(lb.get(lb.curSELEction()[0]))
root = tk.Tk()
root.geometry("400x400")
bt = tk.button(root, text="Search", command=lambda:searchfiles('.png', 'H:\\'))
bt.pack()
lb = tk.ListBox(root)
lb.pack(fill="both", expand=1)
lb.bind("<Double-button>", lambda x: open_file())
root.mainloop()
如何在Python中列出目录的所有文件并将其添加到中list?
以上是大佬教程为你收集整理的Python-如何列出目录的所有文件?全部内容,希望文章能够帮你解决Python-如何列出目录的所有文件?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。