I just ran into a problem, which is probably easy to fix - well, for you guys.
I try to create a directory, change to it, create a file in that directory and appened to that file. Everything works fine - except it marks the directory/file as locked and that isn't very convenient for me.
I am running my script as root, because I need to. When I run it normally that problem doesn't occur. I am on Ubuntu and down below is some example code plus a picture of the permissions of the given file, thanks!
import os
os.makedirs("foo", exist_ok = True)
os.chdir("foo")
with open("oof", "a") as f:
f.write("something" + "\n")
As you said you run the script as root so other users can not access this file.
You can change directory permissions:
from subprocess import call
call(['chmod', 'mode', 'path'])
Related
I'm trying to run a script that works without issue when I run using in console, but causes issue if I try to run it from another directory (via IPython %run <script.py>)
The issue comes from this line, where it references a folder called "Pickles".
with open('Pickles/'+name+'_'+date.strftime('%y-%b-%d'),'rb') as f:
obj = pickle.load(f)
In Console:
python script.py <---works!
In running IPython (Jupyter) in another folder, it causes a FileNotFound exception.
How can I make any path references within my scripts more robust, without putting the whole extended path?
Thanks in advance!
Since running in the console the way you show works, the Pickles directory must be in the same directory as the script. You can make use of this fact so that you don't have to hard code the location of the Pickles directory, but also don't have to worry about setting the "current working directory" to be the directory containing Pickles, which is what your current code requires you to do.
Here's how to make your code work no matter where you run it from:
with open(os.path.join(os.path.dirname(__file__), 'Pickles', name + '_' + date.strftime('%y-%b-%d')), 'rb') as f:
obj = pickle.load(f)
os.path.dirname(__file__) provides the path to the directory containing the script that is currently running.
Generally speaking, it's a good practice to always fully specify the locations of things you interact with in the filesystem. A common way to do this as shown here.
UPDATE: I updated my answer to be more correct by not assuming a specific path separator character. I had chosen to use '/' only because the original code in the question already did this. It is also the case that the code given in the original question, and the code I gave originally, will work fine on Windows. The open() function will accept either type of path separator and will do the right thing on Windows.
You have to use absolute paths. Also to be cross platform use join:
First get the path of your script using the variable __file__
Get the directory of this file with os.path.dirname(__file__)
Get your relative path with os.path.join(os.path.dirname(__file__), "Pickles", f"{name}_{date.strftime('%y-%b-%d')}")
it gives you:
with open(os.path.join(os.path.dirname(__file__), "Pickles", f"{name}_{date.strftime('%y-%b-%d')}"), 'rb') as f:
obj = pickle.load(f)
I have encountered a problem while trying to open a .txt file from the same directory where my source code is located.
When I tried to open the file like this:
with open("pi_digits.txt") as file_object:
contents = file_object.read()
print(contents)
I failed.
I also failed when I typed the whole path:
with open("Users\lukas\Documents\python_work\chapter_10") as file_object:
contents = file_object.read()
print(contents)
But when I typed:
with open("\\Users\\lukas\\Documents\\python_work\\chapter_10\\pi_digits.txt") as file_object:
contents = file_object.read()
print(contents)
I succeeded!
So my question is: Why can't I run the code without error when I enter the following code:
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
Thank you for your answers and sorry if my question was not well constructed.
#Sottvogel
In general, a python instance can be run from many different directories in your computer. One way to check where the running instance is:
import os
os.getcwd()
If you confirm that you are in the same directory of your file, try and see
what the following returns:
os.listdir()
In case your file doesn't appear in the returned string, then there has to be another problem. Make sure you checkout the docs as well.
Hope it helps!
the thing with paths is python is that they are referenced from where you launch the program (current working directory), not from where the file lives. So, I recommend making use of the os and pathlib packages to manage file paths properly.
Why can't I run the code without error when I enter the following code:
It depends from where you execute your python code.
Building on above, where you execute your code implies wether you need to use the file name or it's path.
If you execute your Python code in the same directory as the txt file, then you can use the file's name. However, if it is located elsewhere the script will need to access the file and hence, requires the path to it.
background = pygame.image.load('example.jpg')
nubjuk = pygame.image.load('nubjuk.png')
nubjuk = pygame.transform.scale(nubjuk, (200,90))
This is the code part of the problem and the error message is:
Exception has occurred: error
Couldn't open example.jpg
I think I've tried every solution uploaded in other StackOverflow questions.(os.path ~, absolute path, just anything) However, they don't work.
More weird thing is that it properly worked yesterday, but even though I didn't touch anything it doesn't work today.
What's the problem?
Your code expects the files 'example.jpg' and 'nubjuk.png' to be in the current working directory.
Obviously this is not the case. Either you changed the working directory prior to calling your script or your script changes the working directory.
or you moved the png files to a different directory (or deleted them)
If the .png files are in the same directory than your python script you can do something like that
at the beginning of your file.
import os
MYDIR = os.path.realpath(os.path.dirname(__file__))
and then replace your two image.load lines with
background = pygame.image.load(os.path.join(MYDIR, 'example.jpg'))
nubjuk = pygame.image.load(os.path.join(MYDIR, 'nubjuk.png'))
I have created a small python script. With that I am trying to read a txt file but my access is denied resolving to an no.13 error, here is my code:
import time
import os
destPath = 'C:\Users\PC\Desktop\New folder(13)'
for root, dirs, files in os.walk(destPath):
f=open(destPath, 'r')
.....
Based on the name, I'm guessing that destPath is a directory, not a file. You can do a os.walk or a os.listdir on the directory, but you can't open it for reading. You can only call open on a file.
Maybe you meant to call open on one or more of the items from files
1:
I take it you are trying to access a file to get what's inside but don't want to use a direct path and instead want a variable to denote the path. This is why you did the destPath I'm assuming.
From what I've experienced the issue is that you are skipping a simple step. What you have to do is INPUT the location then use os.CHDIR to go to that location. and finally you can use your 'open()'.
From there you can either use open('[direct path]','r') or destPath2 = 'something' then open(destPath2, 'r').
To summarize: You want to get the path then NAVIGATE to the path, then get the 'filename' (can be done sooner or not at all if using a direct path for this), then open the file.
2: You can also try adding an "r" in front of your path. r'[path]' for the raw line in case python is using the "\" for something else.
3: Try deleting the "c:/" and switching the / to \ or vice versa.
That's all I got, hope one of them helps! :-)
I got this issue when trying to create a file in the path -C:/Users/anshu/Documents/Python_files/Test_files . I discovered python couldn't really access the directory that was under the user's name.
So, I tried creating the file under the directory - C:/Users/anshu/Desktop .
I was able to create files in this directory through python without any issue.
I have recently begun working on a new computer. All my python files and my data are in the dropbox folder, so having access to the data is not a problem. However, the "user" name on the file has changed. Thus, none of my os.chdir() operations work. Obviously, I can modify all of my scripts using a find and replace, but that won't help if I try using my old computer.
Currently, all the directories called look something like this:
"C:\Users\Old_Username\Dropbox\Path"
and the files I want to access on the new computer look like:
"C:\Users\New_Username\Dropbox\Path"
Is there some sort of try/except I can build into my script so it goes through the various path-name options if the first attempt doesn't work?
Thanks!
Any solution will involve editing your code; so if you are going to edit it anyway - its best to make it generic enough so it works on all platforms.
In the answer to How can I get the Dropbox folder location programmatically in Python? there is a code snippet that you can use if this problem is limited to dropbox.
For a more generic solution, you can use environment variables to figure out the home directory of a user.
On Windows the home directory is location is stored in %UserProfile%, on Linux and OSX it is in $HOME. Luckily Python will take care of all this for you with os.path.expanduser:
import os
home_dir = os.path.expanduser('~')
Using home_dir will ensure that the same path is resolved on all systems.
Thought the file sq.py with these codes(your olds):
C:/Users/Old_Username/Dropbox/Path
for x in range:
#something
def Something():
#something...
C:/Users/Old_Username/Dropbox/Path
Then a new .py file run these codes:
with open("sq.py","r") as f:
for x in f.readlines():
y=x
if re.findall("C:/Users/Old_Username/Dropbox/Path",x) == ['C:/Users/Old_Username/Dropbox/Path']:
x="C:/Users/New_Username/Dropbox/Path"
y=y.replace(y,x)
print (y)
Output is:
C:/Users/New_Username/Dropbox/Path
for x in range:
#something
def Something():
#something...
C:/Users/New_Username/Dropbox/Path
Hope its your solution at least can give you some idea dealing with your problem.
Knowing that eventually I will move or rename my projects or scripts, I always use this code right at the beginning:
import os, inspect
this_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
this_script = inspect.stack()[0][1]
this_script_name = this_script.split('/')[-1]
If you call your script not with the full but a relative path, then this_script will also not contain a full path. this_dir however will always be the full path to the directory.