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)).
Related
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)
I was trying to read data from a bunch of textfiles in a directory, but getting an error while opening the file
import os
fileList = os.listdir("Desktop/SLUI")
for txtName in fileList:
#Open the textfile
UIname=str(txtName)
userDTL=open(UIname,'r')
if userDTL.mode=='r':
line=userDTL.readlines()
string1=line[0]
string2=line[1]
string3=line[2]
UserDTL.close()
print(string1)
Here is the error when I try to run this code via cmd.exe
File "C:\Users\*****\Desktop\programName.py", line 24, in <module>
userDTL=open(UIname,'r')
FileNotFoundError: [Errno 2] No such file or directory: 'file1.txt'
It's because os.listdir only displays the name of the files, and to open them you need the whole path.
You need to redefine UIname as such:
UIname=os.path.join("Desktop/SLUI",txtName) # I don't think you need the string conversion.
os.path.join() will properly join two (or more) bits of paths, whichever OS you use.
I'm not really familiar with how Python works on Windows, so you might need to replace "Desktop/SLUI" by the appropriate path to your desktop (C:\Users*****\Desktop).
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()
I am trying to write a program to categorize into folders a large amount of files according to their respective groups indicated in the file name. I wrote the followin code, but when I run it it gives me a file not found error, even though the file is in the given path. I'd appreciate any help in figuring out what is wrong.
import os
old_dir = '/Users/User/Desktop/MyFolder'
for f in os.listdir(old_dir):
file_name, file_ext = os.path.splitext(f)
file_name.split('-')
split_file_name = file_name.split('-')
new_dir = os.path.join(old_dir,
'-'.join(split_file_name[:3]),
split_file_name[5],
f)
os.rename(os.path.join(old_dir, f), new_dir)
Here's the error:
Traceback (most recent call last):
File "/Users/User/Documents/Sort Files into Folders/Sort Files into Folders.py", line 19, in <module>
os.rename(os.path.join(old_dir, f), new_dir)
FileNotFoundError: [Errno 2] No such file or directory: '/Users/User/Desktop/MyFolder/AHA35-3_30x1_12-31-7d-g1a1-ArmPro.jpg' -> '/Users/User/Desktop/MyFolder/AHA35-3_30x1_12-31/ArmPro/AHA35-3_30x1_12-31-7d-g1a1-ArmPro.jpg
os.rename does not automatically create new directories (recursively), if the new name happens to be a filename in a directory that does not exist.
To create the directories first, you can (in Python 3) use:
os.makedirs(dirname, exist_ok=True)
where dirname can contain subdirectories (existing or not).
Alternatively, use os.renames, that can handle new and intermediate directories. From the documentation:
Recursive directory or file renaming function. Works like rename(), except creation of any intermediate directories needed to make the new pathname good is attempted first
os.rename need path, so it should look like:
os.rename(path+old_name, path+new_name)
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.