繁体   English   中英

尝试重命名文件时出现 Python Win 32 错误

[英]Python Win 32 error while trying to rename a file

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

我尝试了什么:

  1. 首先我在程序中没有 file.close() 行,但没有解决问题
  2. 我添加了一行 print(file.closed) 以查看文件是否实际关闭
  3. 我试图从缩进的“with”块中取出 os.rename 。 但我不断收到同样的错误
  4. 我试图从任何块中获取 os.rename 。 但是后来我得到一个 Winerror 123,它说文件名、目录名等不正确。
  5. 我还在尝试 os.rename 时阅读了WindowsError 32Windows Error: 32 when try 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 还很新,所以如果你能给我一些关于我的错误的见解,我不胜感激!

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM