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

Python 使用with open修复os.remove错误会导致字符串错误,python,python-os,Python,Python Os,我已经阅读了之前询问os.remove为何变得越来越强大的案例 WindowsError:[错误32]进程无法访问该文件,因为另一进程正在使用该文件 我曾尝试将with open(csvPath,“r”)用作csvData,但当我这样做时,我开始出现错误: TypeError:“str”对象不支持项分配 如果我用open和os.remove注释掉,那么文件将生成,但我仍然需要删除源文件。我现在不担心第13行的评论,因为我可以稍后修复它,但是我不能删除源文件有点问题 import csv impo

我已经阅读了之前询问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()
导入csv
导入操作系统
导入日期时间
对于os.listdir(“.\Pending”)中的文件:
如果文件.endswith('.csv'):
csvFile=文件
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(打开(csvPath))
#目前只支持逗号分隔。这需要扩大
#确保可以写入目标文件夹
尝试:
xmlData=open(xmlFile'w')
xmlData.write(“”+“\n”)
#必须只有一个顶级标记
xmlData.write(“”+“\n”)
rowNum=0
对于csvData中的行:
如果rowNum==0:
标记=行
#替换标记名中带下划线的空格
对于范围内的i(len(标记)):
标记[i]=标记[i]。替换(“”,“”)
其他:
xmlData.write(“”+“\n”)
对于范围内的i(len(标记)):
xmlData.write(“”+“”)\
+第[i]+'+“\n”行)
xmlData.write(“”+“\n”)
rowNum+=1
xmlData.write(“”+“\n”)
xmlData.close()
#如果转换中没有错误,请从挂起路径中删除
#如何捕获未知错误?转换中可能出现哪些错误?
删除操作系统(csvPath)
除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.path.join(“.\Error”,errorFile))
删除操作系统(错误路径)
日志=打开(日志文件“w”)
log.write(“无法写入已处理的文件夹”)
log.close()
其他:
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.path.join(“.\Error”,errorFile))
删除操作系统(错误路径)
日志=打开(日志文件“w”)
log.write(“文件不是CSV扩展名”)
log.close()

使用它始终是一种很好的做法

with open(filename, 'r') as f:
    dostuff...
因为文件在退出“with”语句后会自动关闭


另一个解决方案是“熊猫”套餐。“pandas”有一个“read_csv”方法,如果您提供csv文件的名称,则在读取后自动关闭csv。比如说,

import pandas

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

如果
csvPath
文件仍处于打开状态,则无法删除该文件。您从未关闭它。是的,但是如果我尝试使用csvData.close()我会得到AttributeError:“\u csv.reader”对象没有属性“close”,请先为它分配另一个变量:
f=open(csvPath);csvData=csv.reader(f)