【问题标题】:Fixing os.remove error using with open causes string error [duplicate]使用 with open 修复 os.remove 错误导致字符串错误 [重复]
【发布时间】:2023-04-08 02:21:01
【问题描述】:

我已经阅读了之前询问为什么 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()

【问题讨论】:

  • 如果csvPath 文件仍处于打开状态,您将无法删除它。你永远不会关闭它。
  • 是的,但如果我尝试使用 csvData.close() 我得到 AttributeError: '_csv.reader' object has no attribute 'close'
  • 先给它分配另一个变量:f = open(csvPath); csvData = csv.reader(f)

标签: python python-os


【解决方案1】:

使用总是好的习惯

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

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


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

import pandas

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多