Brosef
Brosef

Reputation: 3095

Renaming a single file in python

I'm trying to rename an audio file but I keep getting OSError: [Errno 2] No such file or directory.

In my program, each user has a directory that holds the users files. I obtain the path for each user by doing the following:

current_user_path = os.path.join(current_app.config['UPLOAD_FOLDER'], user.username)

/Users/johnsmith/Documents/pythonprojects/project/files/john

Now I want to obtain the path for the existing file I want to rename:

current_file_path = os.path.join(current_user_path,form.currentTitle.data)

/Users/johnsmith/Documents/pythonprojects/project/files/john/File1

The path for the rename file will be:

new_file_path = os.path.join(current_user_path, form.newTitle.data)

/Users/johnsmith/Documents/pythonprojects/project/files/john/One

Now I'm just running the rename command:

os.rename(current_file_path, new_file_path)

Upvotes: 2

Views: 5757

Answers (3)

Sanchayan Sarkar
Sanchayan Sarkar

Reputation: 1

Try changing the current working directory to the one you want to work with. This code below should give you a simple walk through of how you should go about it:

import os
print (os.getcwd())
os.chdir(r"D:\Python\Example")
print (os.getcwd())
print ("start")
def rename_files():
    file_list= os.listdir(r"D:\Python\Example")
    print(file_list)
    for file_name in file_list:
            os.rename(file_name,file_name.translate(None,"0123456789")) rename_files()
print("stop")
print (os.getcwd())

Upvotes: 0

Rajiv Sharma
Rajiv Sharma

Reputation: 7142

you can use os.rename for rename single file.

to avoid

OSError: [Errno 2] No such file or directory.

check if file exist or not.

here is the working example:

import os

src = "D:/test/Untitled003.wav"
dst = "D:/test/Audio001.wav"

if os.path.isfile(src):
    os.rename(src, dst)

Upvotes: 6

James K. Lowden
James K. Lowden

Reputation: 7837

If the OS says there's no such file or directory, that's the gospel truth. You're making a lot of assumptions about where the file is, constructing a path to it, and renaming it. It's a safe bet there's no such file as the one named by current_file_path, or no directory to new_file_path.

Try os.stat(current_file_path), and similarly double-check the new file path with os.stat(os.posixpath.dirname(new_file_path)). Once you've got them right, os.rename will work if you've got permissions.

Upvotes: 2

Related Questions