Как проверить содержимое папки с помощью Python

StackOverflow https://stackoverflow.com/questions/2249132

  •  20-09-2019
  •  | 
  •  

Вопрос

Как вы можете проверить содержимое файла с помощью Python, а затем скопировать файл из той же папки и переместить его в новое место? У меня есть Python 3.1, но я могу так же легко перенести 2.6 Спасибо!

Это было полезно?

Решение

Например

import os,shutil
root="/home"
destination="/tmp"
directory = os.path.join(root,"mydir")
os.chdir(directory)
for file in os.listdir("."):
    flag=""
    #check contents of file ?
    for line in open(file):
       if "something" in line:
           flag="found"
    if flag=="found":
       try:
           # or use os.rename() on local
           shutil.move(file,destination)
       except Exception,e: print e
       else:
           print "success"

Если вы посмотрите на Shutil Doc, под .move () это говорит

shutil.move(src, dst)¶

    Recursively move a file or directory to another location.
    If the destination is on the current filesystem, then simply use rename. 
Otherwise, copy src (with copy2()) to the dst and then remove src.

Я думаю, что вы можете использовать copy2 () для перемещения в другую файловую систему.

Другие советы

os.listdir() а также shutil.move().

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top