On 02/01/17 17:01, anatta anatta wrote: > I am trying to create unsuccessfully source path as > a string 'str7' in part_1 of the code below,
When you say unsuccessfully what do you mean? What do you expect? What do you get? > to be used in part_2 of the code. For that you need to expose it outside the function, the best way to do that is to return it as a value, which you comment suggests you want to do. But the only return is commented out, so you need to tidy that up. But personally I think your function is trying to do too much. You should simplify it to only return the files and have another function that returns the path. Functions that try to do too many things (ie more than one) are notoriously difficult to debug. > When I define the source path explicitly in part_2 > of the code (#sourcePath = r'H://TCVFLDAT'), the > code works right. I'll take your word for it. > How else could I find the path in part-1 and use it in part 2? Return the value (assuming it is the right value) and in part two assign the return from the function to a variable. For my analysis below I've removed all the flag nonsense which is just cluttering things up for now and gone with the ENDS_WITH option as default.... > def fetchFiles(pathToFolder, flag, keyWord): > > _pathToFiles = [] > _fileNames = [] > > for dirPath, dirNames, fileNames in os.walk(pathToFolder): > 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) You could simplify that by putting the selectedFiles line before the selectedPath line and use selectedFiles inside the comprehension. > > # Try to remove empty entries if none of the required files are > in directory > try: > _pathToFiles.remove('') > _imageFiles.remove('') It would probably be better to check if they were empty before putting them in. Since you use the endswith() test I'm thinking there should never be any empty ones in this scenario anyway? > except ValueError: > pass > > #return _pathToFiles, _fileNames Here is the missing return statement but it's not returning what you said you wanted, ie str7 > #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) It might be wise to print the string itself to check you have what you want, I'm not sure you do... But I'm not really sure what you want since your code logic is confusing me a bit here. > str2 = str1.replace(" ", "") #remove white spaces So why did you add it above? Why not just use an empty string in the join? However, more seriously, what affect does this have on any paths/filenames that you found with spaces in them? Is that really what you want? > print 'str2 is', str2 > str3 = str2[13:16] #extract rgeistration > print 'str3 is registration:', str3 I'll assume this is right since I've no idea what format you think your filenames have. However, in general, relying on fixed positions within a string is not a good idea. This might be a valid case for using a regex which can more flexibly match your pattern. But for now just stick with the simple fixed values... > str4 = 'FLDAT' > print 'str4 is: ', str4 > str5 = str3.__add__(str4) You shouldn't really call the dunder methods directly you should use the + operator: str5 = str3 + str4 Or, in this case, save a variable and use the literal: str5 = str3 + 'FLDAT' > print 'str 5 is: ',str5 > str6 = 'H://' > print 'str6 is: ', str5 Did you really mean that? You've already printed str5. And do you really need a double slash after the drive letter? That's usually only needed if using backslashes ('H:\\'). > str7 = str6.__add__(str5) Again you could just use the literals: str7 = 'H://' + str3 = 'FLDAT' > print 'str7 is: ', str7 > > fetchFiles('H://','ENDS_WITH','.FLD') No assignment of any return value here > #### part_2 #### copying files from sourcePath to destPath > > sourcePath = r'str7' This assigns the literal string 'str7' is that what you want? You cannot access the variable str7 that was inside the function. It was a local variable and will have been destroyed by now. > print 'Source path is: ', sourcePath > destPath = r'c://test_o/' > print 'Destination path is: ', destPath > 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: > 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.' You can save some work by using comma separation: print 'File', f,'copied.' No spaces needed and no string additions going on. > 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 >>>> 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 Note you have a mix of // and \ as separators. Probably better to just use one. > 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/ -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor