用Python重命名文件

时间:2013-05-13 12:54:27

标签: python file-handling

我是几天自学成才的蟒蛇新手。我已经对python的运行方式有了基本的了解,但我确实坚持以下几点。

我有一个文本文件列表,它们是邮箱名称的Exchange Server邮件转储。我有数百个这样的文本文件,目前它们的名称格式为Priv_date.txt,例如Priv_02JAN2004.txt。我需要能够告诉他们来自哪个服务器所以在这些文本文件中我想读取具有实际邮件服务器名称的10行(服务器:MAILSERVER1)并将其添加或附加到原始文件名。

我最终想要的是读取MAILSERVER1_PRIV_02JAN2004.txt的文件名。我对自己能做什么和不能对文件路径和名称做些什么感到困惑,但看不出我做错了什么。我已经达到了这个目的:

import os,sys

folder = "c://EDB_TEMP"

for root, dirs, filenames in os.walk(folder):
    for filename in filenames:
        fullpath=os.path.join(root,filename)
        filename_split = os.path.splitext(fullpath)

        #print fullpath
        #print filename

        with open (fullpath, "r") as tempfile:
            for line in tempfile.readlines():
                if "Server:" in line:
                    os.rename(tempfile,+line[10:]+fullpath)

但我一直收到这个错误:

  

错误是TypeError:一元+的错误操作数类型:'str'

2 个答案:

答案 0 :(得分:3)

您的os.rename(tempfile,+line[10:]+fullpath)中有错误,逗号似乎放错地方。

错误基本上表示逗号后面的+不能在字符串之前,即行[10:]。

答案 1 :(得分:2)

此代码适用于您所描述的内容

#Also include Regular Expression module, re
import os,sys,re

#Set root to the folder you want to check
folder = "%PATH_TO_YOUR_FOLDER%"

#Walk through the folder checking all files
for root, dirs, filenames in os.walk(folder):
    #For each file in the folder
    for filename in filenames:
        #Create blank strink for servername
        servername = ''
        #Get the full path to the file
        fullpath=os.path.join(root,filename)
        #Open the file as read only in tempfile
        with open (fullpath, "r") as tempfile:
            #Iterate through the lines in the file
            for line in tempfile.readlines():
                #Check if this line contains "Server: XXXXX"
                serverline= re.findall("Server: [a-zA-Z0-9]+", line)
                #If the line was found
                if serverline:
                    #Split the line around ": " and take second part as server name
                    sname = serverline[0].split(": ")
                    #Set servername variable so isn't lost outside scope of with block
                    servername = sname[1]
        #If a servername was found for that text file
        if len(servername) > 0:
            #Rename the file
            os.rename(fullpath,root+'\\'+servername+filename)

这样做是像往常一样遍历目录,找到每条路径。对于每个文件,它将获取它的路径,打开文件并查找包含Server:SERVERNAME的行。然后它将提取SERVERNAME并将其放入servername变量中。文件完成后,它将被关闭,脚本将检查该文件是否生成了servername字符串。如果是,则通过使用SERVERNAME前缀重命名该文件。

我有一段时间所以决定测试它所以应该做你想做的事情