小唯快跑啊
获取Python 2和3的文件列表我还在这里做了一个简短的视频:Python:如何获取目录中的文件列表os.listdir()或者.....如何获取当前目录中的所有文件(和目录)(Python 3)在Python 3中将文件放在当前目录中的最简单方法是这样。这很简单; 使用os模块和listdir()函数,你将拥有该目录中的文件(以及目录中的最终文件夹,但你不会将文件放在子目录中,因为你可以使用walk - 我将在稍后讨论它)。>>> import os>>> arr = os.listdir()>>> arr['$RECYCLE.BIN', 'work.txt', '3ebooks.txt', 'documents']使用glob我发现glob更容易选择相同类型的文件或共同的东西。请看以下示例:import glob
txtfiles = []for file in glob.glob("*.txt"):
txtfiles.append(file)使用列表理解import glob
mylist = [f for f in glob.glob("*.txt")]使用os.path.abspath获取完整路径名如您所知,您在上面的代码中没有该文件的完整路径。如果您需要具有绝对路径,则可以使用所os.path调用模块的另一个函数_getfullpathname,将您获得的文件os.listdir()作为参数。还有其他方法可以获得完整路径,我们稍后会检查(我更换了,如mexmex所建议的那样,_getfullpathname with abspath)。>>> import os>>> files_path = [os.path.abspath(x) for x in os.listdir()]>>> files_path['F:\\documenti\applications.txt', 'F:
\\documenti\collections.txt']获取所有子目录中的文件类型的完整路径名 walk我发现这对于在许多目录中查找内容非常有用,它帮助我找到了一个我不记得名字的文件:import os# Getting the current work directory (cwd)thisdir = os.getcwd()# r=root, d=directories, f = filesfor r, d, f in os.walk(thisdir):
for file in f:
if ".docx" in file:
print(os.path.join(r, file))os.listdir():获取当前目录中的文件(Python 2)在Python 2中,如果您想要当前目录中的文件列表,则必须将参数设置为“。”。或os.listdir方法中的os.getcwd()。>>> import os>>> arr = os.listdir('.')>>> arr['$RECYCLE.BIN', 'work.txt', '3ebooks.txt', 'documents']进入目录树>>> # Method 1>>> x = os.listdir('..')# Method 2>>> x= os.listdir('/')获取文件:特定目录中的os.listdir()(Python 2和3)>>> import os>>> arr = os.listdir('F:\\python')>>> arr['$RECYCLE.BIN', 'work.txt', '3ebooks.txt', 'documents']使用os.listdir()获取特定子目录的文件import os
x = os.listdir("./content")os.walk('。') - 当前目录>>> import os>>> arr = next(os.walk('.'))[2]>>> arr['5bs_Turismo1.pdf', '5bs_Turismo1.pptx', 'esperienza.txt']glob模块 - 所有文件import globprint(glob.glob("*"))out:['content', 'start.py']next(os.walk('。'))和os.path.join('dir','file')>>> 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)>output
F:\\_python\\dict_class.py
F:\\_python\\programmi.txtnext(os.walk('F:\') - 获取完整路径 - 列表理解>>> [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']os.walk - 获取完整路径 - 子目录中的所有文件x = [os.path.join(r,file) for r,d,f in os.walk("F:\\_python") for file in f]>>>x['F:\\_python\\dict.py', 'F:\\_python\\progr.txt', '
F:\\_python\\readl.py']os.listdir() - 只获取txt文件>>> arr_txt = [x for x in os.listdir() if x.endswith(".txt")]>>> print(arr_txt)['work.txt', '3ebooks.txt']glob - 只获取txt文件>>> import glob>>> x = glob.glob("*.txt")>>> x['ale.txt', 'alunni2015.txt', 'assenze.text.txt', 'text2.txt', 'untitled.txt']使用glob来获取文件的完整路径如果我需要文件的绝对路径:>>> 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其他使用glob如果我想要目录中的所有文件:>>> x = glob.glob("*")使用os.path.isfile来避免列表中的目录import os.path
listOfFiles = [f for f in os.listdir() if os.path.isfile(f)]print(listOfFiles)> output['a simple game.py', 'data.txt', 'decorator.py']使用pathlib(Python 3.4)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如果你想使用列表理解>>> flist = [p for p in pathlib.Path('.').iterdir() if p.is_file()]*您也可以使用pathlib.Path()而不是pathlib.Path(“。”)在pathlib.Path()中使用glob方法import pathlib
py = pathlib.Path().glob("*.py")for file in py:
print(file)输出:stack_overflow_list.py
stack_overflow_list_tkinter.py使用os.walk获取所有和唯一的文件import os
x = [i[2] for i in os.walk('.')]y=[]for t in x:
for f in t:
y.append(f)>>> 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]>>> 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来自Python 3.5的os.scandir()>>> import os>>> x = [f.name for f in os.scandir() if f.is_file()]>>> 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>>>防爆。1:子目录中有多少个文件?在此示例中,我们查找包含在所有目录及其子目录中的文件数。import osdef 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"))> output>'F:\\\python' : 12057 files'例2:如何将目录中的所有文件复制到另一个目录?一个脚本,用于在计算机中查找所有类型的文件(默认值:pptx)并将其复制到新文件夹中。import osimport shutilfrom 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("------------------------")
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')> Output_compiti18\Compito Contabilità 1\conti.txt
_compiti18\Compito Contabilità 1\modula4.txt
_compiti18\Compito Contabilità 1\moduloa4.txt------------------------==> Found in: `_compiti18` : 3 files防爆。3:如何获取txt文件中的所有文件如果您要创建包含所有文件名的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)示例:txt包含硬盘驱动器的所有文件"""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")C:\\的所有文件都在一个文本文件中这是以前代码的较短版本。如果需要从其他位置开始,请更改文件夹从哪里开始查找文件。此代码在我的计算机上生成一个50 MB的文本文件,其中包含少于500.000行,文件包含完整路径。import oswith 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")搜索特定类型文件的功能import osdef searchfiles(extension='.ttf'):
"Create a txt file with all the file of a type"
with open("file.txt", "w", encoding="utf-8") as filewrite:
for r, d, f in os.walk("C:\\"):
for file in f:
if file.endswith(extension):
filewrite.write(f"{r + file}\n")# looking for ttf file (fonts)searchfiles('ttf')