2

我是几天的自学python新手。我对 python 的运行方式有了基本的了解,但我真的坚持以下几点。

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

我想要结束的是读取的文件名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'

4

2 回答 2

3

你有一个错误,你os.rename(tempfile,+line[10:]+fullpath) 的逗号似乎放错了位置。

该错误基本上是说+逗号后面不能位于字符串之前,即 line[10:]。

于 2013-05-13T12:58:42.473 回答
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 为前缀来重命名文件。

我有一些时间,所以决定也测试一下,所以应该做你想做的

于 2013-05-13T13:42:59.197 回答