❶ 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 格式
解决这个问题需要用到PIL库
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)
第二步 当判断文件不是GIF格式的时候转换为GIF格式
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()