[Tutor] Fw: path string

anatta anatta kumarmysore at hotmail.com
Tue Jan 3 10:59:25 EST 2017


Dear Tutor,

Please disregard my request below.

I know the problem!

I have not defined the variable in question as a global variable.


regret the inconvenience caused.


Best.

Kumar.

+


________________________________
From: anatta anatta <kumarmysore at hotmail.com>
Sent: Monday, January 2, 2017 5:01 PM
To: tutor at python.org
Subject: path string

Dear Tutor.

I am trying to create unsuccessfully source path as a string 'str7' in part_1 of the code below, to be used in part_2 of the code.
When I define the source path explicitly in part_2 of the code (#sourcePath = r'H://TCVFLDAT'), the code works right.
How else could I find the path in part-1 and use it in part 2?

######################
Here is my code:
######################


# -*- coding: utf-8 -*-
"""
Created on Wed Jun 01 17:05:07 2016

@author: anatta
"""


# Required module
import os
import shutil
###part_1 ### looking for files to be copied and obtaining source path  ###
# Function for getting files from a folder
def fetchFiles(pathToFolder, flag, keyWord):
        '''     fetchFiles() requires three arguments: pathToFolder, flag and
 keyWord flag must be 'STARTS_WITH' or 'ENDS_WITH' keyWord is a string to
  search the file's name  Be careful, the keyWord is case sensitive and must
  be exact.  Example: fetchFiles('/Documents/Photos/','ENDS_WITH','.jpg')
returns: _pathToFiles and _fileNames '''

        _pathToFiles = []
        _fileNames = []

        for dirPath, dirNames, fileNames in os.walk(pathToFolder):
                if flag == 'ENDS_WITH':
                        selectedPath = [os.path.join(dirPath,item) for item in fileNames if item.endswith(keyWord)]
                        _pathToFiles.extend(selectedPath)

                        selectedFile = [item for item in fileNames if item.endswith(keyWord)]
                        _fileNames.extend(selectedFile)

                elif flag == 'STARTS_WITH':
                        selectedPath = [os.path.join(dirPath,item) for item in fileNames if item.startswith(keyWord)]
                        _pathToFiles.extend(selectedPath)

                        selectedFile = [item for item in fileNames if item.startswith(keyWord)]
                        _fileNames.extend(selectedFile)

                else:
                        print fetchFiles.__doc__
                        break

                # Try to remove empty entries if none of the required files are in directory
                try:
                        _pathToFiles.remove('')
                        _imageFiles.remove('')
                except ValueError:
                        pass

                # Warn if nothing was found in the given path
                #if selectedFile == []:
                        #print 'No files with given parameters were found in:\n', dirPath, '\n'

                #print len(_fileNames), 'files were found is searched folder(s)'

        #return _pathToFiles, _fileNames
        #print _pathToFiles, _fileNames
        print 'path to first tuple file is:', _pathToFiles [0]
        str1 = ' '.join(_pathToFiles [0]) #convert tuple element 0 to string
        print 'length of str1 is: ', len (str1)
        str2 = str1.replace(" ", "") #remove white spaces
        print 'str2 is', str2
        str3 = str2[13:16] #extract rgeistration
        print 'str3 is registration:', str3


        str4 = 'FLDAT'
        print 'str4 is: ', str4
        str5 = str3.__add__(str4)
        print 'str 5 is: ',str5
        str6 = 'H://'
        print 'str6 is: ', str5
        str7 = str6.__add__(str5)
        print 'str7 is: ', str7

        #print _fileNames
        print 'Number of files found: ', len(_fileNames)
fetchFiles('H://','ENDS_WITH','.FLD')

#### part_2 #### copying files from sourcePath to destPath

#sourcePath = r'H://TCVFLDAT'
sourcePath = r'str7'
print 'Source path is: ', sourcePath
destPath = r'c://test_o/'
print 'Destination path is: ', destPath
#ls=os.listdir('.')#list current dir
#print('listing current dir\n')
#print(ls)
for root, dirs, files in os.walk(sourcePath):

    #figure out where we're going
    dest = destPath + root.replace(sourcePath, '')

    #if we're in a directory that doesn't exist in the destination folder
    #then create a new folder
    if not os.path.isdir(dest):
        os.mkdir(dest)
        print 'Directory created at: ' + dest
    else:
        print 'Directory already exists:' + dest

for root, dirs, files in os.walk(sourcePath):
        #figure out where we're going
    dest = destPath + root.replace(sourcePath, '')
    filetype = '.FLD'# name the file ext to be copied
    print 'All files of this type will be copied', filetype
    #loop through all files in the directory
    for f in files:

        #compute current (old) & new file locations
        oldLoc = root + '\\' + f
        newLoc = dest + '\\' + f
        #print 'Old location is:', oldLoc
        #print 'New location is:', newLoc

        if not os.path.isfile(newLoc):
            try:
                #filetype = '.FLD'# name the file ext to be copied
                #print 'All files of this type will be copied', filetype
                filename, file_ext = os.path.splitext(oldLoc)
                print 'filename is:', filename
                print 'file ext is', file_ext
                if file_ext == filetype:
                    shutil.copy2(oldLoc, newLoc)
                    print 'File ' + f + ' copied.'
                else:
                    print 'File ' + f + ' not copied'
            except IOError:
                print 'file "' + f + '" already exists'

####################
Below is the output:
####################


Python 2.7.11 |Anaconda 4.0.0 (64-bit)| (default, Feb 16 2016, 09:58:36) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org

Thank You for Using Anaconda<http://continuum.io/thanks>
continuum.io
How was your experience getting set up? Is there anything you'd like to share with us? We would love to hear your feedback! We'll use it to make Anaconda even better. Send feedback to the Anaconda team



:: Anaconda Cloud<https://anaconda.org/>
anaconda.org
Where packages, notebooks, and environments are shared. Powerful collaboration and package management for open source and private projects. Public projects and ...



>>> runfile('D:/university_2/my_code_2/2017_01_02/get_reg_&_copy_file.py', wdir='D:/university_2/my_code_2/2017_01_02')
path to first tuple file is: H://TCVFLDAT\TCV00000.FLD
length of str1 is:  49
str2 is H://TCVFLDAT\TCV00000.FLD
str3 is registration: TCV
str4 is:  FLDAT
str 5 is:  TCVFLDAT
str6 is:  TCVFLDAT
str7 is:  H://TCVFLDAT
Number of files found:  21
Source path is:  str7
Destination path is:  c://test_o/
>>>


More information about the Tutor mailing list