How do you use the os.rename() function in python 3? - python

I'm trying to rename the file names and extensions of all the files in a directory and move them to a new directory. I've read multiple post on how to do it but for some reason I haven't been successful and I've been stuck on this for 3 days now and feel like I'm doing something careless. Somebody get me on track please.
This is the latest way I've been trying.
import os
previousName = 'Macintosh HD⁩/⁨Users⁩/⁨kunductor/⁨Desktop⁩/⁨folder3/windeffect.asd'
newName = 'Macintosh HD⁩/Users⁩/kunductor⁩/Desktop⁩/folder4/wind.wav'
os.rename(previousName,newName)
When I run the code above I get the message:
Traceback (most recent call last):
File "rename.py", line 7, in <module>
os.rename(previousName,newName)
FileNotFoundError: [Errno 2] No such file or directory
If it matters, I'm using macOS Mojave, version 10.14.2.

I tried replicating the same using Python 3 on Mojave 10.14.2. Use the paths starting from '/Users', and don't include Macintosh HD. The code runs perfectly when both folder3 and folder4 exist. I got a similar error when folder4 was removed, and the error message also specified the paths I passed as parameters.
If that's what you're experiencing, ensure that the directory you're trying to move the file to exists before calling os.rename. This can be done in Python itself by using the os.mkdir method. Since it throws an error if the directory already exists, you can check that by using the os.path.exists method.

this is the code that worked. I think the problem was that i was trying to change a non-audio file to a .wav and the system was rejecting it.
import os
# Function to rename multiple files
def main():
i = 0
for filename in os.listdir('/Users/vfloyd/Desktop/uu/'):
dst ="Kick" + str(i) + ".wav"
src = '/Users/vfloyd/Desktop/uu/'+ filename
dst ='/Users/vfloyd/Desktop/newD/'+ dst
# rename() function will
# rename all the files
os.rename(src, dst)
i += 1
# Driver Code
if __name__ == '__main__':
# Calling main() function
main()

Related

Not finding any solution to [Errno 2]

I'm trying to use a program to read from a file with pi-digits. The program and the text file with the pi-digits are in the same directory, but i still get the error message :
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
Traceback (most recent call last):
File "C:\Python\Python_Work\python_crash_course\files_and_exceptions\file_reader.py", line 1, in <module>
with open('pi_digits.txt') as file_object:
FileNotFoundError: [Errno 2] No such file or directory: 'pi_digits.txt'
I have looked for a solution but haven't found any.
I found a piece of code which supposedly shows me what the working directory is. I get an output that shows a directory that is 2 steps above the directory i have my programs and text file inside.
import os
cwd = os.getcwd() # Get the current working directory (cwd)
files = os.listdir(cwd) # Get all the files in that directory
print("Files in %r: %s" % (cwd, files))
So when i put the pi text document in the directory that the output is showing (>python_work), the program is working. When it does not work is when the text file is in ">files_and_exceptions" which is the same file the program itself is inside. My directory looks like this when it is not working:
>python_work
>python_crash_course
>files_and_exceptions
file_reader.py
pi_digits.txt
show_working_directory.py
And like this when it is working:
>python_work
pi_digits.txt
>python_crash_course
>files_and_exceptions
file_reader.py
show_working_directory.py
I'm new to python and really appreciate any help.
Thanks!
Relative path (one not starting with a leading /) is relative to some directory. In this case (and generally*), it's relative to the current working directory of the process.
In your case, given the information you've provided, for it would be "python_crash_course/files_and_exceptions/pi_digits.txt" in the first case as you appear to be running the script from python_work directory.
If you know the file to be in the same directory as the script itself, you could also say:
import os.path
...
os.path.join(os.path.dirname(__file__), "pi_digits.txt")
instead of "pi_digits.txt". Or the same using pathlib:
from pathlib import Path
...
Path(__file__).with_name("pi_digits.txt")
Actually unless you have a point to anchor to like the script itself, using relative filename / path (using absolute paths brings its own problems too) in the code directly is rather fragile and in that case getting it as a parameter of a function (and ultimately argument of CLI or script call in general) or alternatively reading it from standard input would be more robust.
* I would not make that an absolute statement, because there are situations and functions that can explicitly provide different anchor point (e.g. os.path.relpath or openat(2); or as another example a symlink target)

os.rename fails to rename files for a certain directory

This is my first time using stack overflow so sorry if i make a mistake.
When trying to run this code it will execute fine and give me my properly renamed files.
import os
a = 0
name_target = raw_input("input the prefix of the files you want enumerated")
for filename in os.listdir("."):
if filename.startswith(name_target):
a = int(a) + 1
a = str(a)
no = filename.__len__() - 4
os.rename(filename, filename[:no] + a + '.txt')
Now this is fine as long as the script exists in the same folder as the files are. But I want to be able to use this script with files which are not in the same folder.
I have found that os.listdir('\some\folder\elsewhere') works fine for other directories but when it comes to renaming them withos.rename the code breaks giving me the message:
Traceback (most recent call last):
File "<string>", line 244, in run_nodebug
File "C:\Users\guy\Desktop\otherfolder\renaming_script.py", line 10, in <module>
os.rename(filename, filename[:no] + a + '.txt')
WindowsError: [Error 2] The system cannot find the file specified`
I have no idea what is wrong here please help me.
The problem is that for other directories, you are getting the directory contents properly but when you try and rename the contents simply by using filenames, the program in fact looks it its own directory, and being unable to find the file, throws an error. Instead you should do something as follows:
os.rename('\some\folder\elsewhere\filename.txt', '\some\folder\elsewhere\filename2.txt')
Or, you can also do the following:
directory = '\some\folder\elsewhere'
os.rename(os.path.join(directory, 'filename.txt'), os.path.join(directory, 'filename2.txt'))
Or, you can also change your working directory as follows:
os.chdir('\some\folder\elsewhere')
An then simply call the os.rename method as if you are in the desired directory
os.rename('filename.txt', 'filenam2.txt')
If you use os.listdir(path), you also have to provide the path in the rename: os.rename(path+filename,path+new_name).
Other option is to use os.chdir(desired_path). With this, your os.rename is fine.

Open a Python File in Notepad++ from a Program

I am trying to replicate IDLE's alt + m command (open a module in the sys path) in Notepad++. I like Notepad++ for editing (rather than IDLE), but this is one feature I cannot find.
When alt+m is pressed, I want it to run a program that asks for a module (that's fairly straightforward, so I can do that). My problem is finding the module and then opening it in Notepad++, not simply running the program. In addition, I want it to open in the same instance (same window) in Notepad++, not a new instance.
I've tried this:
import os
f = r"D:\my_stuff\Google Drive\Modules\nums.py"
os.startfile(f, 'notepad++.exe')
However, I get this error:
Traceback (most recent call last):
File '_filePath_', line 3, in <module>
os.startfile(f, 'notepad++.exe')
OSError: [WinError 1155] No application is associated with the specified file for this operation: 'D:\\my_stuff\\Google Drive\\Modules\\nums.py'
How can I fix this?
Also, given a string, such as 'nums.py', how can I find the full path of it? It's going to be in one of two folders: 'D:\\my_stuff\\Google Drive\\Modules' or 'C:\\Python27\Lib' (it could also be in various subfolders in the 'Lib' folder). Alternatively, I could simply do:
try:
fullPath = r'D:\\my_stuff\\Google Drive\\Modules\\' + f
# method of opening file in Notepad++
except (IOError, FileNotFoundError):
fullPath = r'C:\\Python27\\Lib\\' + f
# open in Notepad++
This doesn't account for subfolders and seems rather clunky. Thanks!
If your .py files will be associated w/ notepad++ the os.startfile(f, 'notepad++.exe') will work for you (see ftype).
Unless, you would like to create this association , the following code will open notepad ++ for you:
import subprocess
subprocess.call([r"c:\Program ...Notepad++.exe", r"D:\my_stuff\Google Drive\Modules\nums.py"])
Reference: subprocess.call()

Absolute Path and Relative Path issue in python

How to remove path related problems in python?
For e.g. I have a module test.py inside a directory TEST
**test.py**
import os
file_path = os.getcwd() + '/../abc.txt'
f = open(file_path)
lines = f.readlines()
f.close
print lines
Now, when I execute the above program outside TEST directory, it gives me error:-
Traceback (most recent call last):
File "TEST/test.py", line 4, in ?
f = open(file_path)
IOError: [Errno 2] No such file or directory: 'abc.txt'
how to resolve this kind of problem. Basically this is just a small example that I have given up.
I am dealing with a huge problem of this kind.
I am using existing packages, which needs to be run only from that directory where it exists, how to resolve such kind of problems, so that I can run the program from anywhere I want.
Or able to deal with the above example either running inside TEST directory or outside TEST directory.
Any help.?
I think the easiest thing is to change the current working directory to the one of the script file:
import os
os.chdir(os.path.dirname(__file__))
This may cause problems, however, if the script is also working with files in the original working directory.
Your code is looking at the current working directory, and uses that as a basis for finding the files it needs. This is almost never a good idea, as you are now finding out.
The solution mentioned in the answer by Emil Vikström is a quickfix solution, but a more correct solution would be to not use current working directory as a startingpoint.
As mentioned in the other answer, __file__ isn't available in the interpreter, but it's an excellent solution for your code.
Rewrite your second line to something like this:
file_path = os.path.join(os.path.dirname(__file__), "..", "abc.txt")
This will take the directory the current file is in, join it first with .. and then with abc.txt, to create the path you want.
You should fix similar usage of os.getcwd() elsewhere in your code in the same way.

file error in python

I have the following script:
import os
import stat
curDir = os.getcwd()+'/test'
for (paths, dirs, files) in os.walk(curDir):
for f in files:
if os.stat(f)[stat.ST_SIZE]>0:
print f
and the folder test/:
test_folder:
--test.wav
a.exe
t1
t2
rain.wav
when i run this script with geany it gives the following error:
Traceback (most recent call last):
File "new_folder_deleter.py", line 8, in <module>
if os.stat(f)[stat.ST_SIZE]>0:
OSError: [Errno2] No such file or directory: 'a.exe'
but when I run it with IDLE:
it just prints test.wav in subfolder test_folder
Can anyone explain why it is so and how I can fix it?
P.S:
My aim is to browse all files and delete files with specified sizes.
You need to specify a full path for os.stat, unless the file is in the current working directory. The simplest way to fix this is to change the WD before trying to access the files:
curDir = os.getcwd()+'/test'
os.chdir(curDir)
A more general solution is to pass the full path to os.stat:
if os.stat(os.path.join(paths, f))[stat.ST_SIZE]>0:
print f
I am not quite sure why IDLE does not produce an error here, though.
The filename is only the basename. You need to use os.path.join(path, f).
The list of files that's returned in the files component from os.walk() is just the file names, without the path. Before you can perform any operations on those files (including stat()), you need to reassemble the path to the file.
The os.walk function returns file and directory names relative to current folder, so you need to os.stat(os.path.join(paths, f)).

Categories