Renaming files in Python: No such file or directory - python

If I try to rename files in a directory, for some reason I get an error.
I think the problem may be that I have not inserted the directory in the proper format ?
Additional info:
python 2 &
linux machine
OSError: [Errno 2] No such file or directory
Though it prints the directories content just fine. What am I doing wrong?
import os
for i in os.listdir("/home/fanna/Videos/strange"):
#print str(i)
os.rename(i, i[:-17])

os.rename() is expecting the full path to the file you want to rename. os.listdir only returns the filenames in the directory. Try this
import os
baseDir = "/home/fanna/Videos/strange/"
for i in os.listdir( baseDir ):
os.rename( baseDir + i, baseDir + i[:-17] )

Suppose there is a file /home/fanna/Videos/strange/name_of_some_video_file.avi, and you're running the script from /home/fanna.
i is name_of_some_video_file.avi (the name of the file, not including the full path to it). So when you run
os.rename(i, i[:-17])
you're saying
os.rename("name_of_some_video_file.avi", "name_of_some_video_file.avi"[:-17])
Python has no idea that these files came from /home/fanna/Videos/strange. It resolves them against the currrent working directory, so it's looking for /home/fanna/name_of_some_video_file.avi.

I'm a little late but the reason it happens is that os.listdir only lists the items inside that directory, but the working directory remains the location where the python script is located.
So to fix the issue add:
os.chdir(your_directory_here)
just before the for loop where your_directory_here is the directory you used for os.listdir.

Related

Streamlip app not searching files in the good directory

I am trying to run a Streamlit app importing pickle files and a DataFrame. The pathfile for my script is :
/Users/myname/Documents/Master2/Python/Final_Project/streamlit_app.py
And the one for my DataFrame is:
/Users/myname/Documents/Master2/Python/Final_Project/data/metabolic_syndrome.csv
One could reasonably argue that I only need to specify df = pd.read_csv('data/df.csv') yet it does not work as the Streamlit app is unexpectedly not searching in its directory:
FileNotFoundError: [Errno 2] No such file or directory: '/Users/myname/data/metabolic_syndrome.csv'
How can I manage to make the app look for the files in the good directory (the one where it is saved) without having to use absolute pathfiles ?
you can use os.getcwd() to get the Current Working Directory. Read up on what this means exactly, fe here
See the sample script below on how to use it. I'm using os.sep for OS agnostic filepath separators.
import os
print(os.getcwd())
relative_path = "data"
full_path = f"{os.getcwd()}{os.sep}{relative_path}"
print(full_path)
filename = "somefile.csv"
full_file_path = f"{full_path}{os.sep}{filename}"
print(full_file_path)
with open(full_file_path) as infile:
for line in infile.read().splitlines():
print(line)
In which directory are you standing when you are running your code?
From your error message I would assume that you are standing in /Users/myname/ which makes python look for data as a subdirectory of /Users/myname/.
But if you first change directory to /Users/myname/Documents/Master2/Python/Final_Project and then run your code from there I think it would work.

Python says it can't find the file I am trying to rename even though it can read the file name

Im tryin to append a short string to every '.png' file. But when I run it, it says cannot find the file. But I know it's there and I can see it in the folder.
Is there anything I need to do?
Here is my script:
import os
for file in os.listdir("./pics"):
if file.endswith(".png"):
newFileName = "{0}_{2}{1}".format(*os.path.splitext(file) + ("z4",))
os.rename(file, newFileName)
Here is the error message I get...02.png is the first file in the folder:
fileNotFoundError: [WinError 2] The system cannot find the file
specified: '02.png' -> '02_z4.png'
It's odd though because it gets the filename, in this case, 02.png. So if it can read the file name, why can't it find it?
Thanks!
I thought my comment might be enough, but for clarity I'll provide a short answer.
02.png doesn't exist relative to your working directory. You need to specify the path to the file for os.rename so you need to include the directory.
import os
for file in os.listdir("./pics"):
if file.endswith(".png"):
newFileName = "/pics/{0}_{2}{1}".format(*os.path.splitext(file) + ("z4",)) # Notice the ./pics
os.rename(os.path.join('pics', file), newFileName)
The name returned from os.listdir() gives the filename, not the full path. So you need to rename pics/02.png to pics/02_zf.png. Right now you don't include the directory name.

How to load dependencies and subfolders in Pycharm?

I am so new with python and pycharm and i got confuse!!
When I run my project in pycharm it gives me an error about not finding the path of my file. The physical file path is:
'../Project/BC/RequiredFiles/resources/a_reqs.csv'
My project working directory is "Project/BC" and the project running file (startApp.sh) is there too. but the .py file that wants to work with a_req.csv is inside the "RequiredFiles" folder. There is the following code in the .py file:
reqsfile = os.getcwd() + "/resources/a_reqs.csv"
it returns: '../Project/BC/resources/a_reqs.csv'
instead of: '../Project/BC/resources/RequiredFiles/a_reqs.csv'
while the .py file is in "RequiredFiles" the os.getcwd() must include it too. but it does not.
The problem is that i can not change the addressing code. because this code works in another IDE and other people who work with the code in other platform or OS do not have any problem. I am working in mac OS and if i am not mistaken the code works with windows!!
So, how can i tell Pycharm (in mac) to see and load "RequiredFiles" folder as the subfolder of my working directory!!!
os.getcwd returns the current working directory of the process (which may be the directory where startApp.sh is located or another one, depending on the PyCharm's run configuration setting, or, if you start the program from the command line, the directory in which you execute the command).
To make a path independent on the current working directory, you can take the directory where your Python file is located and build the path from it:
os.path.dirname(__file__) + "/resources/a_reqs.csv"
From your question what I see is:
reqsfile = os.getcwd() + "/resources/a_reqs.csv"
Which produces: "../Project/BC/resources/a_reqs.csv", whereas your desired output is
"../Project/BC/resources/RequiredFiles/a_reqs.csv". Since we know os.getcwd is returning "/Project/BC/", then to get your desired result you should be doing:
reqsfile = os.getcwd() + "/resources/RequiredFiles/a_reqs.csv"
But since you want the solution to work with or without the RequiredFiles subdirectory you could apply a conditional solution, ie something like:
import os.path
if os.path.exists(os.getcwd() + "/resources/RequiredFiles/a_reqs.csv"):
reqsfile = os.getcwd() + "/resources/RequiredFiles/a_reqs.csv"
else:
reqsfile = os.getcwd() + "/resources/a_reqs.csv"
This solution will set the reqsfile to the csv in the RequiredFiles directory if the directory exists, and thus will work for you. On the other-hand, if the RequiredFiles directory doesn't exist, it will default to the csv in /resources/.
Typically when groups collaborate on projects, the maintain the same file hierarchy so that these types of issues are avoided, so you might want to consider moving the csv from /RequiredFiles/ to /resources/.

Using absolute path with os.stat

I would like to iterate through a directories file listing and check the permissions of each file. The following code works well for iterating through each file
path = "/home/bob/test"
for i in os.listdir(path):
osstat = oct(os.stat(i).st_mode & 0777)
But the os.stat commands fails as it needs to run against the absolute path.
I know this as if I run the script from /home/bob/test/ it works (as it runs against the working directory)
Should I use:
os.chdir(path)
Or is there a cleaner way (I don't want to get into changing directories back and forth all the time).
Erm...
osstat = oct(os.stat(os.path.join(path, i)).st_mode & 0777)

move a file to the current directory using shutil module

I know this may sound really stupid, but how can I move a file in a directory a user browsed to ( I named mine filedir) to the current directory I am in?
for example: I have a file called "pages.html" in "C:\webs". How can I move that file to the current working directory "."?
This is my code:
shutil.move(filedir, "*.*")
#I got errors using this code..
Is there another way to say current directory, other than "." ?
The second argument of shutil.move specifies a directory, not a glob mask:
import os.path
shutil.move(os.path.join(filedir, "pages.html"), os.getcwd())
should work.
It would be very helpful if you posted the error message and the complete traceback. However, to get the current working directory you can use os.getcwd(). As long as filedir points to a file and not the directory this should work.
filedir = r"C:\webs\pages.html"
shutil.move(filedir, os.getcwd())

Categories