请选择 进入手机版 | 继续访问电脑版
设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
查看: 31769|回复: 33

【每日一坑 4】 查找文件

[复制链接]

174

主题

45

好友

10万

积分

管理员

Rank: 9Rank: 9Rank: 9

发表于 2013-12-19 20:02:50 |显示全部楼层
上一个坑,取出字符串中的数字,在论坛上出现了好几种方法。除了基本的遍历判断来做外,还有一些简便的python解法:

1.正则
''.join(re.findall(r'\d+',text))

2.isdigit
''.join([i for i in text if i.isdigit()])

[i for i in test]这是一种生成list的方法,通过后面的if可以增加生成时的过滤条件。这种写法在python中很常用。

3.filter
filter(lambda x: x.isdigit(), text)

filter是一个过滤器,其中的lambda表达式是过滤的条件。这个稍微高深了一点,有兴趣的同学可以去搜索一下“lambda表达式”。

今天的坑,准备做一些跟文件相关的操作。先来点最基本的:

找出指定文件夹中的所有以txt结尾的文件,包括所有嵌套的子文件夹。
#==== Crossin的编程教室 ====#
微信ID:crossincode
网站:http://crossincode.com
回复

使用道具 举报

1

主题

0

好友

41

积分

新手上路

Rank: 1

发表于 2013-12-19 20:11:07 |显示全部楼层

回帖奖励 +5

  1. # coding:utf-8
  2. import os
  3. import fnmatch

  4. for root, dirs, files in os.walk('.'):
  5.     for file in files:
  6.         if fnmatch.fnmatch(file, "*.txt"):
  7.             print file
复制代码
回复

使用道具 举报

0

主题

0

好友

389

积分

中级会员

Rank: 3Rank: 3

发表于 2013-12-19 21:29:22 |显示全部楼层

回帖奖励 +5

findThem.py
  1. #! /usr/bin/env python
  2. # coding:utf-8

  3. import os
  4. import sys

  5. if __name__ == "__main__":
  6.     if len(sys.argv) != 1 and os.path.exists(sys.argv[1]):
  7.         themAll = []
  8.         for dirpath, dirnames, filenames in os.walk(sys.argv[1]):
  9.             for filename in filenames:              
  10.                 if os.path.splitext(filename)[1] == '.txt':
  11.                     themAll.append(os.path.join(dirpath, filename))
  12.         print themAll
  13.     else:
  14.         print 'Please input like this:./findThem.py /home/fl0w'
复制代码
回复

使用道具 举报

0

主题

0

好友

17

积分

新手上路

Rank: 1

发表于 2013-12-19 21:33:13 |显示全部楼层

回帖奖励 +5

本帖最后由 HAO 于 2013-12-19 21:43 编辑
  1. # -*- coding: utf-8 -*-

  2. import os
  3. from sys import argv

  4. filename, path = argv

  5. txt_files = []

  6. if os.path.isdir(path):
  7.     for dir_path, dir_names, file_names in os.walk(path):
  8.         for file_name in file_names:
  9.             if file_name.endswith('.txt'):
  10.                 txt_files.append(file_name)


  11. print txt_files
复制代码
回复

使用道具 举报

0

主题

0

好友

389

积分

中级会员

Rank: 3Rank: 3

发表于 2013-12-19 21:39:39 |显示全部楼层
HAO 发表于 2013-12-19 21:33

这样不能找出嵌套的子文件夹中的以.txt结尾的文件
回复

使用道具 举报

0

主题

0

好友

17

积分

新手上路

Rank: 1

发表于 2013-12-19 21:42:41 |显示全部楼层
fl0w 发表于 2013-12-19 21:39
这样不能找出嵌套的子文件夹中的以.txt结尾的文件

哈哈。谢谢提醒。
回复

使用道具 举报

0

主题

0

好友

65

积分

注册会员

Rank: 2

发表于 2013-12-19 23:28:49 |显示全部楼层

回帖奖励 +5

本帖最后由 liucy 于 2013-12-19 23:29 编辑
  1. # coding:utf-8
  2. import os
  3. import fnmatch

  4. def findfile(inputdir):
  5.     txtlist = []
  6.     for parent, dirnames, filename in os.walk(inputdir):
  7.         for filenames in filename:
  8.             txtlist.append(filenames)
  9.         return fnmatch.filter(txtlist, '*.txt')

  10. if __name__ == "__main__":
  11.     inputdir1 = input("Please input your dir(like this: '/Users/lemon') : ")
  12.     print findfile(inputdir1)
复制代码
回复

使用道具 举报

0

主题

0

好友

101

积分

注册会员

Rank: 2

发表于 2013-12-20 17:40:16 |显示全部楼层

回帖奖励 +5

本帖最后由 shallecker 于 2013-12-20 17:45 编辑

带路径+txt
  1. # coding:utf-8
  2. import os, re

  3. for i in os.walk('d:'+os.sep):
  4.     for txt in i[2]:
  5.         try:
  6.             txt = re.match(r'(.*)(\.txt)', txt).group(0)
  7.             print os.path.join(i[0], txt)
  8.         except:
  9.             pass
复制代码
回复

使用道具 举报

0

主题

0

好友

79

积分

注册会员

Rank: 2

发表于 2013-12-21 01:59:29 |显示全部楼层
长长的c又来了,有点乱没来得急整理。。。
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4. #include <dirent.h>
  5. #include <errno.h>
  6. #include <string.h>
  7. #include <sys/stat.h>

  8. #define PATH_SIZE 4096

  9. char *path;

  10. int show_txt(char *);

  11. int main(int argc, const char *argv[])
  12. {
  13.   if (argc != 2) {
  14.     printf("Usage: ./a.out <path of dir>\n");
  15.     exit(1);
  16.   }

  17.   path = malloc(PATH_SIZE);
  18.   strcpy(path, argv[1]);

  19.   show_txt(path);

  20.   free(path);

  21.   return 0;
  22. }

  23. int show_txt(char *path)
  24. {
  25.   struct stat statbuf;
  26.   struct dirent *dirp;
  27.   DIR *dp;
  28.   char *ptr;

  29.   int len = strlen(path);

  30.   if (lstat(path, &statbuf) < 0) {  /* lstat error */
  31.     perror("lstat error");
  32.     exit(1);
  33.   }

  34.   if (S_ISDIR(statbuf.st_mode) == 0) {  /* not a directory */
  35.       if (strcmp(&path[len-4], ".txt") == 0) {
  36.       printf("%s\n", path);
  37.     }
  38.     return 0;
  39.   }

  40.   ptr = path + len;
  41.   *ptr++ = '/';
  42.   *ptr = 0;

  43.   if ((dp = opendir(path)) == NULL) { /* open directory error */
  44.     perror("opendir error");
  45.     exit(1);
  46.   }

  47.   /* iterate the directory(dp)'s each element*/
  48.   while ((dirp = readdir(dp)) != NULL) {  
  49.     /* ignore the present directory and the last directory */
  50.     if (strcmp(dirp->d_name, ".") == 0 || strcmp(dirp->d_name, "..") == 0)
  51.       continue;

  52.     strcpy(ptr, dirp->d_name);  /* append the element's name to path */
  53.     show_txt(path); /* call the show_txt(char*) recursively */
  54.   }

  55.   ptr[-1] = 0;
  56.   closedir(dp);
  57.   return 0;
  58. }
复制代码
回复

使用道具 举报

0

主题

0

好友

134

积分

注册会员

Rank: 2

发表于 2013-12-21 16:57:58 |显示全部楼层
  1. import os,fnmatch
  2. def find_txt(root,patterns='*.txt'):#定义主函数,接受目录与所要匹配的拓展名为参数
  3.     list_of_txt=[]#列表储存txt文件名
  4.     for dirname,subdir,filenames in os.walk(root):#使用os。walk(遍历包括子目录下所有文件),生成三组列表,第一组为当前目录地址,第二组为当下前目录下的文件夹名(没有则返回一个空列表),第三组为当前目录的所有文件
  5.         for name in filenames:#遍历每组文件名
  6.             if fnmatch.fnmatch(name,patterns):#用fnmatch。fnmatch寻找匹配的文件
  7.                 list_of_txt.append(name)#加入列表
  8.     return list_of_txt
  9. if __name__=='__main__':
  10.     dir=raw_input('directory:')
  11.     txtfiles=find_txt(dir)
  12.     print txtfiles
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-3-29 05:32 , Processed in 0.018013 second(s), 22 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部