使用open修复os.remove错误会导致字符串错误

时间:2019-01-30 16:04:49

标签: python python-os

我已阅读了之前询问os.remove为什么得到

的案例
  

WindowsError:[错误32]该进程无法访问文件,因为该文件正在被另一个进程使用。

我尝试将with与open(csvPath,“ r”)一起用作csvData,但是当我这样做时,我开始收到错误消息:

  

TypeError:'str'对象不支持项目分配

如果我用open和os.remove注释掉了,则将生成文件,但是我仍然需要删除源文件。我现在不担心第13行的注释,因为稍后可以修复该问题,但是我无法删除源文件有点问题。

import csv
import os
import datetime

for file in os.listdir(".\Pending"):
    if file.endswith('.csv'):
        csvFile = file
        csvPath = (os.path.join(".\Pending",csvFile))

        xmlFile = os.path.join('.\Processed',os.path.splitext(csvFile)[0] + '_' + datetime.datetime.today().strftime('%Y%m%d') + '.xml')

        csvData = csv.reader(open(csvPath))
        # Right now only comma delimitation is supported. This needs to be extended

        # Make sure it is possible to write to the destination folder
        try:
            xmlData = open(xmlFile, 'w')
            xmlData.write('<?xml version="1.0"?>' + "\n")
            # there must be only one top-level tag
            xmlData.write('<csv_data>' + "\n")

            rowNum = 0
            for row in csvData:
                if rowNum == 0:
                    tags = row
                    # replace spaces w/ underscores in tag names
                    for i in range(len(tags)):
                        tags[i] = tags[i].replace(' ', '_')
                else: 
                    xmlData.write('<row>' + "\n")
                    for i in range(len(tags)):
                        xmlData.write('    ' + '<' + tags[i] + '>' \
                                    + row[i] + '</' + tags[i] + '>' + "\n")
                    xmlData.write('</row>' + "\n")

                rowNum +=1

            xmlData.write('</csv_data>' + "\n")
            xmlData.close()

            # IF there are no errors in the transform, delete from the pending path
            # How do I catch unknown errors? What errors are possible within the transform?
            os.remove(csvPath)

        except IOError:
            errorFile = file
            errorPath = (os.path.join(".\Pending",errorFile))
            logFile = os.path.join('.\Error',os.path.splitext(errorFile)[0] + '_' + datetime.datetime.today().strftime('%Y%m%d') + '.txt')

            os.rename(os.path.join(".\Error",errorFile))
            os.remove(errorPath)

            log = open(logFile, 'w')
            log.write("Cannot write to the Processed folder")
            log.close()

    else:
        errorFile = file
        errorPath = (os.path.join(".\Pending",errorFile))
        logFile = os.path.join('.\Error',os.path.splitext(errorFile)[0] + '_' + datetime.datetime.today().strftime('%Y%m%d') + '.txt')

        os.rename(os.path.join(".\Error",errorFile))
        os.remove(errorPath)

        log = open(logFile, 'w')
        log.write("File is not a CSV extension")
        log.close()

1 个答案:

答案 0 :(得分:1)

使用始终是一种好习惯

with open(filename, 'r') as f:
    dostuff...

因为该文件在退出“ with”语句后自动关闭。


另一种解决方案涉及“ pandas”软件包。 “ pandas”具有一个“ read_csv”方法,如果您提供了csv文件的名称,则该方法会在读取后自动关闭csv。例如,

import pandas

data = pandas.read_csv(filename)
# file is already closed here