Python的一些问题,求指教

baron0037 2016-08-27 11:45:34
最近在学Python,接触的不是很深,有一些问题
1. 在指定的文件夹内有txt文件,如何去遍历搜索到这些文件,随后去读取所有的文件内容(如下图目录结构)

读文件好像可以用read,readline这些方法吧?主要是遍历搜索怎么弄


2.搜索到的txt文件内的比如"ABC"的字符,怎么将其替换为"abc"。好像能用.replace?

还有一个深层问题:
3.在txt文件内读取到了这样的内容"RP=XXX/XXX/XXX/abc.f3d",怎么读取到abc.f3d。随后在脚本里将其保存到一个已知的路径文件地址中,然后在移动到指定的文件夹中?
稍微解释一下,abc.f3d是我工作相关的一些模型文件,在已知路径下可以通过别的软件打开,现在就是需要通过读取目录下的txt文件里的模型文件后缀,把它移动到一个新的文件目录里....

烦请各位能够帮忙下,谢谢了
...全文
251 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
baron0037 2016-09-04
  • 打赏
  • 举报
回复
引用 4 楼 lonlon29 的回复:
[quote=引用 2 楼 lonlon29 的回复:]
import os
import re
import shutil
import time

def MainFunction():
    a = raw_input ("""
1. Replace Content on Folder
2. Copy Models

Press Any Key to Exit
        
Please choose : """)
    if (a == "1" or a == "2"):
        
        TestCasesDir = raw_input ("Please Input your folder Path: ")

        if a == "1":
            s = raw_input("Please Input what words you want to find: ")
            p = raw_input("Please Input what words you want to replace: ")

            #TestCasesDir = "C:\\Users\\t_zhanj\\Desktop\\Cases"
            if os.path.exists(TestCasesDir):
                ReplaceContentOnDir(TestCasesDir,s,p)
            else:
                print "This folder not exist!"
                
        if a == "2":
            s = 'RP'
            CopyMyModels(TestCasesDir,s)
            
    else:
        exit(0)

def ReplaceContentOnDir(TestCasesDir,s,p):
    Dir = os.listdir(TestCasesDir)       
    for myFile in Dir:
        TxtFile = os.path.join(TestCasesDir,myFile)
       
        if "txt" in myFile:
            #print "File Path is: " + TxtFile #Show the txt file path(Should open this)
            #print "File Name is: " + myFile #Show the txt file name
            print "================================ Start ================================"
            print myFile+ " is reading....."   
            files = open (TxtFile,'r') #read mode
            content = files.read()
            files.close()

            if s in content:
                print "Found word: " + s + " in File " + myFile
                
                files = open (TxtFile,'w') # write mode
                files.writelines(content.replace (s, p))
                files.close()
                print s + " has been replaced as " + p + " Success!"
                
                #f = open (TxtFile,'r')
                #content = f.read()
                #f.close()
                
                
            else:
                print s + " Not found on File!"
            #f.close()
            print "================================ Finish ==============================="
    CountineOrExit()

def CopyMyModels(TestCasesDir,s):
    Dir = os.listdir(TestCasesDir)       
    for myFile in Dir:
        TxtFile = os.path.join(TestCasesDir,myFile)
        
        if "txt" in myFile:
            i=0
            print "=============Start on Copy Sample Files================="
            print myFile+ " is reading"   
            files = open (TxtFile,'r') #read mode

            AllLines = files.readlines()
            #print AllLines,type(AllLines)

            # Use Readlines to read all content on txt file and for cycle to convert to str type 
            for eachline in AllLines:
                #replace " as space in order to clear some noise
                eachline = eachline.replace('"','') 
                #print eachline
                match = re.search(r'^([a-zA-Z]:|//[a-zA-Z0-9_.$ -]+/[a-z0-9_.$ -]+)?((?:/|^)(?:[^//:*?"<>|\r\n]+/)+)', eachline)
                extname = re.findall(r'\[^.\\/:*?"<>|\r\n]+$', eachline)
                filename = re.findall(r'[^\\/:*?"<>|\r\n]+$' , eachline)
        
                if s in eachline:
                    if match:
                        filepath = match.group(2)
                        
                    else:  
                        filepath = ""
                        
                        
                    #Use method find to find the index of what you want to search.Here I found word:RP
                    search = 'RP'
                    start = 0
                    index = eachline.find(search, start)
                    #Should add 3 to get the real path of model,RP in 27,should get it start after "RP=" that add 3 index
                    index +=3 
                    #print index

                    #Use split to get the model from which type
                    #print "file path is " + filepath[index:]
                    SubFolder = filepath[index:].split('/')[-2]
                    #print "file name is " + filename[0]
                    #print "SubFolder is " +SubFolder
                    
                    myFusionPath = r'C:\\Users\\t_zhanj\\AppData\\Local\\Autodesk\\webdeploy\\dev\\70f3c4c6ffa63f9c51e83d924d85542ac308a9bc'
                    ModelPath = os.path.join (myFusionPath,filepath[index:],filename[0])
                    #print "ModelPath is " + ModelPath

                    if os.path.exists(ModelPath):

                        TargetFolder = r'C:\\Users\\t_zhanj\\Desktop\\Cases\\ModelTestingFolder'
                        TargetFolder = os.path.join(TargetFolder,SubFolder)

                        
                        if os.path.exists(TargetFolder):         
                            print TargetFolder + " existed!"
                        else:
                            #Makedirs can create multi level folder
                            #mkdir only crate one level folder
                            os.makedirs(TargetFolder)
                            #print TargetFolder + " create success!"

                        # Copy Files use shutil copy method
                        # shutil (sourceFolder,TargetFolder)
                        CopiedModelPath = os.path.join(TargetFolder,filename[0])
                        print CopiedModelPath
                        
                        if os.path.exists(CopiedModelPath):
                            #get the name without [''] on list,so use filename[0]
                            print filename[0] + " has been copied,do not need copy again!"
                            
                        else:
                            shutil.copy (ModelPath,TargetFolder)
                            #print "CopiedModelPath is " + CopiedModelPath
                            #get the name without [''] on list,so use filename[0]
                            print "Copy " + filename[0]+ " Success! "
                            
                           

                    else:
                        print "Model path " + ModelPath + " not existed!"
                        

                    
        """
            if i == 0:
                print s + " didn't found on " + myFile
            elif i == 1:
                print s + " has been found for " + str(i) + " time on " + myFile
            else:
                print s + " have been found for " + str(i) + " times on " + myFile
           """         
                
        files.close()
    print "=============Finish on Copy Sample Files================="
    CountineOrExit()


def CountineOrExit():
    IsExit = raw_input ("Countine(Y) or Exit(N)? ")
    while(1):
        if IsExit.upper() == "Y":
            MainFunction()
        elif IsExit.upper() == "N":
            exit(0)
        else:
            print "You have inputed the illegal character,try again!"
            CountineOrExit()
            break
            
            
            
if __name__=='__main__':
    MainFunction()

    

楼主看看吧,基本上应该能实现这些功能了,有问题可以再问
发现个小问题,这个代码只能在一个文件夹进行搜索遍历,不能深层遍历

for root,dirnames,filenames in os.walk(TestCasesDir):
        for myFile in filenames:
            TxtFile = os.path.join(root,myFile)
            if "txt" in myFile:       
在 if "txt" in myFile: 补上搜索所有文件的遍历循环就行了[/quote] 非常感谢,解决了好多问题,再次谢谢
lonlon29 2016-09-04
  • 打赏
  • 举报
回复
引用 2 楼 lonlon29 的回复:
import os
import re
import shutil
import time

def MainFunction():
    a = raw_input ("""
1. Replace Content on Folder
2. Copy Models

Press Any Key to Exit
        
Please choose : """)
    if (a == "1" or a == "2"):
        
        TestCasesDir = raw_input ("Please Input your folder Path: ")

        if a == "1":
            s = raw_input("Please Input what words you want to find: ")
            p = raw_input("Please Input what words you want to replace: ")

            #TestCasesDir = "C:\\Users\\t_zhanj\\Desktop\\Cases"
            if os.path.exists(TestCasesDir):
                ReplaceContentOnDir(TestCasesDir,s,p)
            else:
                print "This folder not exist!"
                
        if a == "2":
            s = 'RP'
            CopyMyModels(TestCasesDir,s)
            
    else:
        exit(0)

def ReplaceContentOnDir(TestCasesDir,s,p):
    Dir = os.listdir(TestCasesDir)       
    for myFile in Dir:
        TxtFile = os.path.join(TestCasesDir,myFile)
       
        if "txt" in myFile:
            #print "File Path is: " + TxtFile #Show the txt file path(Should open this)
            #print "File Name is: " + myFile #Show the txt file name
            print "================================ Start ================================"
            print myFile+ " is reading....."   
            files = open (TxtFile,'r') #read mode
            content = files.read()
            files.close()

            if s in content:
                print "Found word: " + s + " in File " + myFile
                
                files = open (TxtFile,'w') # write mode
                files.writelines(content.replace (s, p))
                files.close()
                print s + " has been replaced as " + p + " Success!"
                
                #f = open (TxtFile,'r')
                #content = f.read()
                #f.close()
                
                
            else:
                print s + " Not found on File!"
            #f.close()
            print "================================ Finish ==============================="
    CountineOrExit()

def CopyMyModels(TestCasesDir,s):
    Dir = os.listdir(TestCasesDir)       
    for myFile in Dir:
        TxtFile = os.path.join(TestCasesDir,myFile)
        
        if "txt" in myFile:
            i=0
            print "=============Start on Copy Sample Files================="
            print myFile+ " is reading"   
            files = open (TxtFile,'r') #read mode

            AllLines = files.readlines()
            #print AllLines,type(AllLines)

            # Use Readlines to read all content on txt file and for cycle to convert to str type 
            for eachline in AllLines:
                #replace " as space in order to clear some noise
                eachline = eachline.replace('"','') 
                #print eachline
                match = re.search(r'^([a-zA-Z]:|//[a-zA-Z0-9_.$ -]+/[a-z0-9_.$ -]+)?((?:/|^)(?:[^//:*?"<>|\r\n]+/)+)', eachline)
                extname = re.findall(r'\[^.\\/:*?"<>|\r\n]+$', eachline)
                filename = re.findall(r'[^\\/:*?"<>|\r\n]+$' , eachline)
        
                if s in eachline:
                    if match:
                        filepath = match.group(2)
                        
                    else:  
                        filepath = ""
                        
                        
                    #Use method find to find the index of what you want to search.Here I found word:RP
                    search = 'RP'
                    start = 0
                    index = eachline.find(search, start)
                    #Should add 3 to get the real path of model,RP in 27,should get it start after "RP=" that add 3 index
                    index +=3 
                    #print index

                    #Use split to get the model from which type
                    #print "file path is " + filepath[index:]
                    SubFolder = filepath[index:].split('/')[-2]
                    #print "file name is " + filename[0]
                    #print "SubFolder is " +SubFolder
                    
                    myFusionPath = r'C:\\Users\\t_zhanj\\AppData\\Local\\Autodesk\\webdeploy\\dev\\70f3c4c6ffa63f9c51e83d924d85542ac308a9bc'
                    ModelPath = os.path.join (myFusionPath,filepath[index:],filename[0])
                    #print "ModelPath is " + ModelPath

                    if os.path.exists(ModelPath):

                        TargetFolder = r'C:\\Users\\t_zhanj\\Desktop\\Cases\\ModelTestingFolder'
                        TargetFolder = os.path.join(TargetFolder,SubFolder)

                        
                        if os.path.exists(TargetFolder):         
                            print TargetFolder + " existed!"
                        else:
                            #Makedirs can create multi level folder
                            #mkdir only crate one level folder
                            os.makedirs(TargetFolder)
                            #print TargetFolder + " create success!"

                        # Copy Files use shutil copy method
                        # shutil (sourceFolder,TargetFolder)
                        CopiedModelPath = os.path.join(TargetFolder,filename[0])
                        print CopiedModelPath
                        
                        if os.path.exists(CopiedModelPath):
                            #get the name without [''] on list,so use filename[0]
                            print filename[0] + " has been copied,do not need copy again!"
                            
                        else:
                            shutil.copy (ModelPath,TargetFolder)
                            #print "CopiedModelPath is " + CopiedModelPath
                            #get the name without [''] on list,so use filename[0]
                            print "Copy " + filename[0]+ " Success! "
                            
                           

                    else:
                        print "Model path " + ModelPath + " not existed!"
                        

                    
        """
            if i == 0:
                print s + " didn't found on " + myFile
            elif i == 1:
                print s + " has been found for " + str(i) + " time on " + myFile
            else:
                print s + " have been found for " + str(i) + " times on " + myFile
           """         
                
        files.close()
    print "=============Finish on Copy Sample Files================="
    CountineOrExit()


def CountineOrExit():
    IsExit = raw_input ("Countine(Y) or Exit(N)? ")
    while(1):
        if IsExit.upper() == "Y":
            MainFunction()
        elif IsExit.upper() == "N":
            exit(0)
        else:
            print "You have inputed the illegal character,try again!"
            CountineOrExit()
            break
            
            
            
if __name__=='__main__':
    MainFunction()

    

楼主看看吧,基本上应该能实现这些功能了,有问题可以再问
发现个小问题,这个代码只能在一个文件夹进行搜索遍历,不能深层遍历

for root,dirnames,filenames in os.walk(TestCasesDir):
        for myFile in filenames:
            TxtFile = os.path.join(root,myFile)
            if "txt" in myFile:       
在 if "txt" in myFile: 补上搜索所有文件的遍历循环就行了
lonlon29 2016-09-02
  • 打赏
  • 举报
回复
import os
import re
import shutil
import time

def MainFunction():
    a = raw_input ("""
1. Replace Content on Folder
2. Copy Models

Press Any Key to Exit
        
Please choose : """)
    if (a == "1" or a == "2"):
        
        TestCasesDir = raw_input ("Please Input your folder Path: ")

        if a == "1":
            s = raw_input("Please Input what words you want to find: ")
            p = raw_input("Please Input what words you want to replace: ")

            #TestCasesDir = "C:\\Users\\t_zhanj\\Desktop\\Cases"
            if os.path.exists(TestCasesDir):
                ReplaceContentOnDir(TestCasesDir,s,p)
            else:
                print "This folder not exist!"
                
        if a == "2":
            s = 'RP'
            CopyMyModels(TestCasesDir,s)
            
    else:
        exit(0)

def ReplaceContentOnDir(TestCasesDir,s,p):
    Dir = os.listdir(TestCasesDir)       
    for myFile in Dir:
        TxtFile = os.path.join(TestCasesDir,myFile)
       
        if "txt" in myFile:
            #print "File Path is: " + TxtFile #Show the txt file path(Should open this)
            #print "File Name is: " + myFile #Show the txt file name
            print "================================ Start ================================"
            print myFile+ " is reading....."   
            files = open (TxtFile,'r') #read mode
            content = files.read()
            files.close()

            if s in content:
                print "Found word: " + s + " in File " + myFile
                
                files = open (TxtFile,'w') # write mode
                files.writelines(content.replace (s, p))
                files.close()
                print s + " has been replaced as " + p + " Success!"
                
                #f = open (TxtFile,'r')
                #content = f.read()
                #f.close()
                
                
            else:
                print s + " Not found on File!"
            #f.close()
            print "================================ Finish ==============================="
    CountineOrExit()

def CopyMyModels(TestCasesDir,s):
    Dir = os.listdir(TestCasesDir)       
    for myFile in Dir:
        TxtFile = os.path.join(TestCasesDir,myFile)
        
        if "txt" in myFile:
            i=0
            print "=============Start on Copy Sample Files================="
            print myFile+ " is reading"   
            files = open (TxtFile,'r') #read mode

            AllLines = files.readlines()
            #print AllLines,type(AllLines)

            # Use Readlines to read all content on txt file and for cycle to convert to str type 
            for eachline in AllLines:
                #replace " as space in order to clear some noise
                eachline = eachline.replace('"','') 
                #print eachline
                match = re.search(r'^([a-zA-Z]:|//[a-zA-Z0-9_.$ -]+/[a-z0-9_.$ -]+)?((?:/|^)(?:[^//:*?"<>|\r\n]+/)+)', eachline)
                extname = re.findall(r'\[^.\\/:*?"<>|\r\n]+$', eachline)
                filename = re.findall(r'[^\\/:*?"<>|\r\n]+$' , eachline)
        
                if s in eachline:
                    if match:
                        filepath = match.group(2)
                        
                    else:  
                        filepath = ""
                        
                        
                    #Use method find to find the index of what you want to search.Here I found word:RP
                    search = 'RP'
                    start = 0
                    index = eachline.find(search, start)
                    #Should add 3 to get the real path of model,RP in 27,should get it start after "RP=" that add 3 index
                    index +=3 
                    #print index

                    #Use split to get the model from which type
                    #print "file path is " + filepath[index:]
                    SubFolder = filepath[index:].split('/')[-2]
                    #print "file name is " + filename[0]
                    #print "SubFolder is " +SubFolder
                    
                    myFusionPath = r'C:\\Users\\t_zhanj\\AppData\\Local\\Autodesk\\webdeploy\\dev\\70f3c4c6ffa63f9c51e83d924d85542ac308a9bc'
                    ModelPath = os.path.join (myFusionPath,filepath[index:],filename[0])
                    #print "ModelPath is " + ModelPath

                    if os.path.exists(ModelPath):

                        TargetFolder = r'C:\\Users\\t_zhanj\\Desktop\\Cases\\ModelTestingFolder'
                        TargetFolder = os.path.join(TargetFolder,SubFolder)

                        
                        if os.path.exists(TargetFolder):         
                            print TargetFolder + " existed!"
                        else:
                            #Makedirs can create multi level folder
                            #mkdir only crate one level folder
                            os.makedirs(TargetFolder)
                            #print TargetFolder + " create success!"

                        # Copy Files use shutil copy method
                        # shutil (sourceFolder,TargetFolder)
                        CopiedModelPath = os.path.join(TargetFolder,filename[0])
                        print CopiedModelPath
                        
                        if os.path.exists(CopiedModelPath):
                            #get the name without [''] on list,so use filename[0]
                            print filename[0] + " has been copied,do not need copy again!"
                            
                        else:
                            shutil.copy (ModelPath,TargetFolder)
                            #print "CopiedModelPath is " + CopiedModelPath
                            #get the name without [''] on list,so use filename[0]
                            print "Copy " + filename[0]+ " Success! "
                            
                           

                    else:
                        print "Model path " + ModelPath + " not existed!"
                        

                    
        """
            if i == 0:
                print s + " didn't found on " + myFile
            elif i == 1:
                print s + " has been found for " + str(i) + " time on " + myFile
            else:
                print s + " have been found for " + str(i) + " times on " + myFile
           """         
                
        files.close()
    print "=============Finish on Copy Sample Files================="
    CountineOrExit()


def CountineOrExit():
    IsExit = raw_input ("Countine(Y) or Exit(N)? ")
    while(1):
        if IsExit.upper() == "Y":
            MainFunction()
        elif IsExit.upper() == "N":
            exit(0)
        else:
            print "You have inputed the illegal character,try again!"
            CountineOrExit()
            break
            
            
            
if __name__=='__main__':
    MainFunction()

    

楼主看看吧,基本上应该能实现这些功能了,有问题可以再问
fengfeng86 2016-09-02
  • 打赏
  • 举报
回复
谢谢3楼,学习了。 谢谢3楼,学习了。 谢谢3楼,学习了。
baidu_29183065 2016-08-28
  • 打赏
  • 举报
回复
这程式可找寻指定文件夹之后所有指定档案,读取并印出其内容 遍历可以用os.walk , 起首一堆常量,比如 startdir='.', 表示由当前件夹开始搜索,若要由c:\data开始,应该写成 startdir = 'c:\\data' 其他的不解自明. #1 的功能是文件中每一句中有'ABC'的替换为 'abc' 至要如何写回至档案,这个不难,楼主自己想想吧. #2 的功能是文件中每一句中有'abc.f3d'的,并传回其索引值,即abc.f3d的位置,若句字是: 012345678abc.f3d 索引值=9 其他细节工序,也不是很难,楼主自己参详吧,不然就是copycat了..

import os,sys

whichfile = 'test'  #所有名称中包含test的文件
whichext = '.txt'   #所有txt文件
startdir = '.'
findstr = 'ABC'
replacestr = 'abc'
searchstr = 'abc.f3d'

for root, dirs, files in os.walk(startdir, topdown=False):
	for name in files:
		if whichext in name and whichfile in name:
			thisname = os.path.join(root, name)
			print('\nfile:[',thisname,']\npress enter to read this file...')
			input()
			with open(thisname, 'r') as f:
				for line in f.readlines():
					#1 newline = line.replace(findstr, replacestr)
					#2 myindex = line.find(searchstr) ...return index
					print(line,end='')

37,720

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧