简体   繁体   中英

Python Win 32 error while trying to rename a file

I have a folder with several csv-files in it. I have to change the filename of every file with a string that I find in the file. So I tried the script below. It looks like it is working until I try to rename the file.

What did I try:

  1. First I didn't have the file.close() line in the program, but did didn't fix the problem
  2. I added a line print(file.closed) to see if the file was actually closed
  3. I tried to get the os.rename out of the indented 'with' block. But I keep getting the same error
  4. I tried to get the os.rename out of any block. But then I get a Winerror 123, where it sais that the filename , directoryname etc. is incorrect.
  5. I also read the questions WindowsError 32 while trying to os.rename and Windows Error: 32 when trying to rename file in python .
  6. I understood that maybe I had to close the file with f.close since this is the handler, but that didn't work as well.

The code that I tried:

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)

I hope somebody can give me some tips and explain what I am doing wrong. Pretty new to Python, so if you can give me some insight in my mistakes, than it's appreciated!

Thank you for your comments and time. It seemed that one of the files that was opened was still busy in some process and therefore the code didn't work. I first closed all the applications that were running, but that didn't work. After that I restarted the computer and the script worked fine!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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