導航:首頁 > 編程語言 > pythonfilelist

pythonfilelist

發布時間:2022-07-25 12:07:50

python 怎麼獲取路徑下的所有文件

#可以使用os.listdir()

importos

#指定的目錄
path="/xxxx/xx/"
filelist=[]
forfinos.listdir():
ifos.path.isdir(f):
filelist.append(f)

#列印出所有文件的列表
printfilelist

❷ 用python實現一個本地文件搜索功能。

import re,os
import sys
def filelist(path,r,f):
"""
function to find the directions and files in the given direction
according to your parameters,fileonly or not,recursively find or not.
"""
file_list = []
os.chdir(path)
filename = os.listdir(path)
if len(filename) == 0:
os.chdir(os.pardir)
return filename
if r == 1: ##
if f == 0: # r = 1, recursively find directions and files. r = 0 otherwise.
for name in filename: # f = 1, find files only, f = 0,otherwise.
if os.path.isdir(name): ##
file_list.append(name)
name = os.path.abspath(name)
subfile_list = filelist(name,r,f)
for n in range(len(subfile_list)):
subfile_list[n] = '\t'+subfile_list[n]
file_list += subfile_list
else:
file_list.append(name)
os.chdir(os.pardir)
return file_list
elif f == 1:
for name in filename:
if os.path.isdir(name):
name = os.path.abspath(name)
subfile_list = filelist(name,r,f)
for n in range(len(subfile_list)):
subfile_list[n] = '\t'+subfile_list[n]
file_list += subfile_list
else:
file_list.append(name)
os.chdir(os.pardir)
return file_list
else:
print 'Error1'
elif r == 0:
if f == 0:
os.chdir(os.pardir)
return filename
elif f == 1:
for name in filename:
if os.path.isfile(name):
file_list.append(name)
os.chdir(os.pardir)
return file_list
else:
print 'Error2'
else:
print 'Error3'

'''
f = 0:list all the files and folders
f = 1:list files only
r = 1:list files or folders recursively,all the files and folders in the current direction and subdirection
r = 0:only list files or folders in the current direction,not recursively

as for RE to match certern file or dirction,you can write yourself, it is easier than the function above.Just use RE to match the result,if match,print;else,pass
"""

❸ python的目錄遍歷操作遇到一點小問題,請網友看看,謝謝了

forfilenameinfilelist:
filepath=os.path.join(path,filename)
ifos.path.isdir(filepath):
dirList(filepath)
allfile.append(filepath)##

和下面有什麼區別嗎?

forfilenameinfilelist:
filepath=os.path.join(path,filename)
allfile.append(filepath)##
ifos.path.isdir(filepath):
dirList(filepath)

要實現不列印目錄,應該這樣寫:

forfilenameinfilelist:
filepath=os.path.join(path,filename)
ifos.path.isdir(filepath):
dirList(filepath)
else:
allfile.append(filepath)##

❹ Python如何查找以數字命名的文件

遍歷文件夾下找到所有文件

判斷當前目錄下文件的文件名是否是純數字的,然後加入到列表中輸出。

importos
num_filelist=[]
forroot,dirs,filesinos.walk(r"E: est"):
fortmpinfiles:
(shotname,extension)=os.path.splitext(tmp)
ifshotname.isalnum():
num_filelist.append(os.path.join(root,tmp))

printnum_filelist

❺ python的文件處理

問題表述看不明白
感覺應該是用正則做

❻ python怎樣實現 先找到文件夾下的所有文件夾,再把這些文件夾下的文件復制到新的文件夾里

#!/usr/bin/envpython
#-*-coding:utf-8-*-


importos
importshutil
importlogging
importdatetime

logging.basicConfig(level=logging.INFO,
format='%(asctime)s%(filename)s[line:%(lineno)d]%(levelname)s%(message)s',
datefmt='%a,%d%b%Y%H:%M:%S',
filename='D:Scriptsmove_file.log',
filemode='a+')

defupload_file(src_path,dst_path):
#目標目錄是否存在,不存在則創建
ifnotos.path.exists(os.path.dirname(dst_path)):
os.makedirs(os.path.dirname(dst_path))

#本地文件是否存在,存在則移動到目標目錄下
ifos.path.exists(src_path):
shutil.move(src_path,dst_path)

defmain(path):
count=0
forroot,dirs,filesinos.walk(path):
forfinfiles:
count+=1
local_file_path=os.path.join(root,f)
upload_file(local_file_path,local_file_path.replace("xxx","zzz"))
logging.info(str(datetime.datetime.now())+":"+str(count))

if__name__=='__main__':
path=r"D:xxx"
try:
main(path)
exceptExceptionase:
logging.error(e)

剛好剛寫完一個。

❼ python 文本文件中查找指定的字元串

編寫一個程序,能在當前目錄以及當前目錄的所有子目錄下查找文件名包含指定字元串的文件,並列印出絕對路徑。
import os
class SearchFile(object):

def __init__(self,path='.'):
self._path=path
self.abspath=os.path.abspath(self._path) # 默認當前目錄

def findfile(self,keyword,root):
filelist=[]
for root,dirs,files in os.walk(root):
for name in files:
fitfile=filelist.append(os.path.join(root, name))
#print(fitfile)
print(os.path.join(root, name))
#print(filelist)
print('...........................................')
for i in filelist:
if os.path.isfile(i):
#print(i)
if keyword in os.path.split(i)[1]:
print('yes!',i) # 絕對路徑
#else:
#print('......no keyword!')

def __call__(self):
while True:
workpath=input('Do you want to work under the current folder? Y/N:')
if(workpath == ''):
break
if workpath=='y' or workpath=='Y':
root=self.abspath # 把當前工作目錄作為工作目錄
print('當前工作目錄:',root)
dirlist=os.listdir() # 列出工作目錄下的文件和目錄
print(dirlist)
else:
root=input('please enter the working directory:')
print('當前工作目錄:',root)
keyword=input('the keyword you want to find:')
if(keyword==''):
break
self.findfile(keyword,root) # 查找帶指定字元的文件

if __name__ == '__main__':
search = SearchFile()
search()

❽ 怎麼用python把多個圖片變成gif 格式

fromPILimportImage
importos
filelist=[]
path=os.getcwd()
files=os.listdir(path)
forfinfiles:
if(os.path.isfile(path+'/'+f)):
if(os.path.splitext(f)[1]==".BMP"):
filelist.append(f)
if(os.path.splitext(f)[1]==".JPG"):
filelist.append(f)
if(os.path.splitext(f)[1]==".PNG"):
filelist.append(f)
if(os.path.splitext(f)[1]==".TIF"):
filelist.append(f)
forinfileinfilelist:
outfile=os.path.splitext(infile)[0]+".gif"
ifinfile!=outfile:
try:
Image.open(infile).save(outfile)
print"CoverttoGIFsuccessfully!"
exceptIOError:
print"Thisformatcannotsupport!",infile

❾ python 怎麼實現兩台伺服器上批量復制文件

1、把excel里文件名那一列復制,粘進一個空白的文本文件,命名為filelist.txt,上傳到伺服器。

2、在伺服器上使用腳本導出,python腳本 fileCp.py 。

代碼示例:
#! python
#coding:utf-8

##!/usr/bin/python
# Filename : fileCp.py
import sys
import os
import shutil

fileList='filelist.txt'
targetDir='files'

filedir = open(fileList)
line = filedir.readline()
log = open('running.log','w')
while line:
line = line.strip('\n');
basename = os.path.basename(line)
exists = os.path.exists(line)
if exists :
print ' '+line+' to '+os.getcwd()+'/'+targetDir+'/'+basename
log.write(' '+line+' to '+os.getcwd()+'/'+targetDir+'/'+basename+'\r\n')
shutil.(line,targetDir+'/'+basename)
else:
print line+' not exists'
log.write(line+' not exists'+'\r\n')
line = filedir.readline()
log.close()

閱讀全文

與pythonfilelist相關的資料

熱點內容
登錄伺服器發生錯誤怎麼回事 瀏覽:270
松下空氣能壓縮機 瀏覽:936
萬能源碼播放器 瀏覽:966
串口伺服器如何轉發 瀏覽:357
如何下載Ck電影部app 瀏覽:744
解壓文具筆袋簡單 瀏覽:288
android百度坐標轉換 瀏覽:367
文件公私鑰加密傳輸 瀏覽:665
python矩陣維度 瀏覽:927
華佗舌診源碼 瀏覽:897
解壓壓縮包有一個錯誤怎麼辦 瀏覽:966
怎麼在手機上設立文件夾 瀏覽:232
雲幫手伺服器搭建教程 瀏覽:785
惠普默認存在哪個文件夾 瀏覽:493
建立桌面圖標文件夾 瀏覽:86
python怎麼跳過異常繼續執行 瀏覽:315
單片機驅動可控硅 瀏覽:294
遼寧沈陽最新代理伺服器ip地址 瀏覽:565
如何安裝用友通伺服器 瀏覽:827
python怎麼將輸入轉為整數類型 瀏覽:608