2015-01-15 36 views
0

我很新的蟒蛇,但我想用它来执行以下任务:的Python:读取多个文件,并将它们转移到一个目录根据其内容

  1. 读取目录
  2. 所有文件
  3. 在文件的所有行中查找特定字符
  4. 如果此字符在文件中仅存在一次,则将该文件复制到特定目录中。

我尝试下面的代码:

#! /usr/bin/python 

import glob 
import shutil 



path = '/xxxx/Dir/*.txt' 
files=glob.glob(path) 
for file in files:  
    f=open(file) 
    f.read() 
    total = 0 
    for line in f: 
     if "*TPR_4*" in line: 
      total_line = total + 1 
      if total_line == 1: 
       shutil.copy(f, 'xxxx/Test/') 
f.close() 

但是,它不工作。 有什么建议吗?

+0

它是否复制,如果你让它总是通过测试? – 2015-01-15 17:12:59

+0

谢谢,答案是否定的。 – efrem 2015-01-15 17:13:35

回答

1

逻辑不完全正确,你也混在totaltotal_lineshutil.copy取名称,而不是对象作为参数。并且请注意,if .. in line不使用通配符语法,即搜索TPR_4,请使用'TPR_4'而不是'*TPR_4*'。请尝试以下操作:

#! /usr/bin/python  
import glob 
import shutil 

path = '/xxxx/Dir/*.txt' 
files=glob.glob(path) 
for file in files:  
    f=open(file) 
    total = 0 
    for line in f: 
     if "TPR_4" in line: 
      total += 1 
      if total > 1: 
       break # no need to go through the file any further 
    f.close() 
    if total == 1: 
     shutil.copy(file, 'xxxx/Test/') 
+0

谢谢,但它不工作。 – efrem 2015-01-15 17:28:30

+0

什么具体不工作?我在一组测试文件上试了一下,它做了我理解它应该做的事情。 – 2015-01-15 17:29:11

+0

我有一个文件只包含TPR_4字符串的一行。在文件夹Dir中有更多的.txt文件。我运行它,Test文件夹是空的,上面提到的文件应该在那里。 – efrem 2015-01-15 17:30:35

2

shutil.copy()将文件名作为参数未打开的文件。您应该更改您的来电:

shutil.copy(file, 'xxxx/Test/') 

另外:file是一个可怜的名字的选择。这是一个内置函数的名字。

+0

谢谢,但仍然无法正常工作。 – efrem 2015-01-15 17:19:02

0

我为您的问题写了一些代码,也许这对您有好处。

import os, shutil 

dir_path = '/Users/Bob/Projects/Demo' 
some_char = 'abc' 
dest_dir = "/Users/Bob/tmp" 
for root, dirs, files in os.walk(dir_path): 
    for _file in files: 
     file_path = os.path.join(root, _file) 
     copy = False 
     with open(file_path, 'r') as f: 
      while True: 
       line = f.readline() 
       if not line: 
        break 
       if str(line).find(some_char) > -1: 
        copy = True 
        break 
      if copy: 
       shutil.copy(file_path, dest_dir) 
       print file_path, ' copy...' 
相关问题