【问题标题】:Python Win 32 error while trying to rename a file尝试重命名文件时出现 Python Win32 错误
【发布时间】:2020-12-26 00:20:15
【问题描述】:

我有一个文件夹,里面有几个 csv 文件。我必须使用在文件中找到的字符串更改每个文件的文件名。所以我尝试了下面的脚本。在我尝试重命名文件之前,它似乎可以正常工作。

我做了什么:

  1. 首先我在程序中没有 file.close() 行,但没有解决问题
  2. 我添加了一行 print(file.closed) 来查看文件是否真的关闭了
  3. 我试图将 os.rename 从缩进的“with”块中取出。但我一直收到同样的错误
  4. 我试图将 os.rename 从任何块中取出。但后来我得到一个 Winerror 123,它说文件名、目录名等不正确。
  5. 我还阅读了WindowsError 32 while trying to os.renameWindows Error: 32 when trying to rename file in python 的问题。
  6. 我知道也许我必须使用 f.close 关闭文件,因为这是处理程序,但这并不奏效。

我试过的代码:

for f in glob.glob("/path/*.csv"):
    with open(f, "r") as file:
        #read the lines in the csv-file
        data = file.read()
        #search the lines that have been read for a pattern and save that in "search"
        search = re.findall("some_pattern", data)
        #The result was a list. With this line I tried to change it into a string
        file.close()
        Listtostring = ''.join([str(elem) for elem in search])
        #I only want to use a part of the match in the new file name
        name = Listtostring.replace("part_of_string", "")
        os.rename(f,f+name)

我希望有人能给我一些提示并解释我做错了什么。对 Python 很陌生,所以如果你能给我一些关于我的错误的见解,那将不胜感激!

【问题讨论】:

  • 如果你得到一个ERROR_INVALID_NAME,那么你传递的路径名是无效的。我无法理解为什么有人会认为关闭文件句柄可以解决该错误。
  • 我不明白为什么 os.rename(f, f+name) 在我的 Mac 上工作,但在 Windows 计算机上却不行。这可能是个问题吗?
  • 不知道你的代码为什么能工作确实是个问题。
  • 感谢您的 cmets 和时间。似乎打开的文件之一在某个进程中仍然很忙,因此代码不起作用。我首先关闭了所有正在运行的应用程序,但这不起作用。之后我重新启动计算机,脚本运行良好!

标签: python windows rename csc


【解决方案1】:

感谢您的 cmets 和时间。似乎打开的文件之一在某个进程中仍然很忙,因此代码不起作用。我首先关闭了所有正在运行的应用程序,但这不起作用。之后我重新启动计算机,脚本运行正常!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 2014-01-26
    • 2021-09-14
    • 1970-01-01
    • 2017-12-10
    • 1970-01-01
    • 2019-07-07
    • 2021-04-10
    相关资源
    最近更新 更多