import os
def rename(directory):
for name in os.listdir(directory):
print(name)
os.rename(name,"0"+name)
path = input("Enter the file path")
rename(path)
I want to rename every file in a certain directory so that it adds a 0 to the beginning of the file name, however when I try to run the code it comes up with this error:
(FileNotFoundError: [WinError 2] The system cannot find the file specified: '0.jpg' -> '00.jpg')
I'm sure that there is a file in there named 0.jpg and I'm not sure what the problem is.
As written you're looking for a file named 0.jpg in the working directory. You want to be looking in the directory you pass in.
So instead do:
os.rename(os.path.join(directory,name),
os.path.join(directory,'0'+name))
You cannot use an absolute path, unless your terminal is in that directory.
Hence, you can do as in the following:
import os
def rename(directory):
os.chdir(directory) # Changing to the directory you specified.
for name in os.listdir(directory):
print(name)
os.rename(name,"0"+name)
I am agreeing with mechanical_meat's answer that "filename" is used to mean the full/absolute path name. The below will also work.
os.rename((directory + name), (directory + '0' + name))
Related
I have the following code (file path details kept anonymous):
def stu_activities():
downloadsList = os.listdir("***/Downloads")
destination = "."
for file_name in downloadsList:
if file_name.startswith("Stu_"):
shutil.copyfile(file_name,destination)
stu_activities()
When I run it, it gives me this error:
FileNotFoundError: [Errno 2] No such file or directory: 'Stu_activity.pptx'
How is it that it claims the file is not found yet it still found it?
I assume that your real code does not contain "***/Downloads" but a real path.
os.listdir() returns the filename, but not the full path to the filename.
shutil.copyfile() on the other hand needs the full path of the file.
Further the destination of shutil.copyfile() must be a file name and not a directory
def stu_activities():
dir_to_List = "/your/path/Downloads"
downloadsList = os.listdir(dir_to_list)
destination = "."
for file_name in downloadsList:
if file_name.startswith("Stu_"):
shutil.copyfile(
os.path.join(dir_to_list, file_name) ,
os.path.join(destination, file_name))
stu_activities()
I have the following file which I would like to read, as you can see its incomplete:
file = 'dir2/file.hdf5'
However, I would like to get the full path of file (*):
'/home/user/git_hub_repo/dir1/dir2/file.hdf5'
However, when I do:
from pathlib import Path
filename = Path('dir2/file.hdf5').resolve()
print(filename)
I get:
'/home/user/git_hub_repo/dir2/file.hdf5'
Which is wrong because a dir1 is missing in the retrieved path, how can I get (*) path
Note, that in my terminal i am in:
/home/user/git_hub_repo/
If your current directory is
/home/user/git_hub_repo/
and your file is in
/home/user/git_hub_repo/dir1/dir2/file.hdf5
You should change this
file = 'dir2/file.hdf5'
to
file = 'dir1/dir2/file.hdf5'
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)
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)
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.
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())
I am trying to use the listdir function from the os module in python to recover a list of filenames from a particular folder.
here's the code:
import os
def rename_file():
# extract filenames from a folder
#for each filename, rename filename
list_of_files = os.listdir("/home/admin-pc/Downloads/prank/prank")
print (list_of_files)
I am getting the following error:
OSError: [Errno 2] No such file or directory:
it seems to give no trouble in windows, where you start your directory structure from the c drive.
how do i modify the code to work in linux?
The code is correct. There should be some error with the path you provided.
You could open a terminal and enter into the folder first. In the terminal, just key in pwd, then you could get the correct path.
Hope that works.
You could modify your function to exclude that error with check of existence of file/directory:
import os
def rename_file():
# extract filenames from a folder
#for each filename, rename filename
path_to_file = "/home/admin-pc/Downloads/prank/prank"
if os.exists(path_to_file):
list_of_files = os.listdir(path_to_file)
print (list_of_files)
I am getting error while trying to change the Current directory to a different folder in python. My code is as below:
I take PATH_DIR as input from user and the user passes absolute path.
files[]
for directories in os.listdir(PATH_DIR):
files.append(directories)
for dir in files:
abs = os.path.abspath(dir)
print abs
os.chdir(abs)
In my compilation trail I give the PATH_DIR as C:\Python27\Scripts and the directories in this folder are 'WIN7' 'WIN8'. When I execute the program, I get an error as below.
WindowsError: [Error 2] The system cannot find the file specified: 'C:\Python27\Scripts\WIN7'
In principle, the command os.chdir() is some how adding a '\' character before every '\' in the directory path. Can you please help me solve this issue.
os.chdir(abs)
You are trying to cd into FILE.
os.listdir() will return full content of given directory.
You need to check whether entity is a directory with os.path.isdir()
import os
PATH_DIR = '.'
files = []
for directory in os.listdir(PATH_DIR):
print os.path.isdir(os.path.join('.', directory))
if os.path.isdir(os.path.join('.', directory)):
files.append(directory)
print files
for directory in files:
abs_path = os.path.abspath(directory)
print abs_path
os.chdir(abs_path)