I created a project where my main.py script is in root folder Project. I have a utils directory inside and I want to get the path to this directory. I made a function which saves a .pdf file in my utils directory:
with open(os.path.abspath('utils/' + self.object.object_name+ '.pdf'), 'wb') as f:
f.write(pdf)
but I get an error:
IOError: [Errno 2] No such file or directory: '/home/documents/office/projects/me/utils/d.pdf'
How can I change os.path.abspath to do it the right way?
I want to get into utils directory always.
What you need is defining the path. And you can keep it relative.
yourPath = './utils/'
yourFileName = self.object.object_name+ '.pdf'
yourFullFileName = yourPath+yourFileName
and finally
with open(yourFullFileName, 'wb') as f:
f.write(pdf)
UPDATE
Following the small course Scott Hunter gave me, (cf his comment) I make amends. It follows that the correct way to build your path is :
working_dir = os.path.dirname(__file__)# __file__ is the full name of your working script
yourFullFileName = os.path.join(working_dir, 'util', self.object.object_name + "." + 'pdf')
By doing so, there is no assumption about the (operating-system dependent) separator.
Related
I am trying to make a keylogger, it works on my computer but when i turn it into an executable it gives me an error "Python failed to execute script keylogger" I think its a path problem because its static and every computer have a diffrent directory, i am a beginner i could use some help.
files = ["log.txt", "info.txt", "clipboard.txt", "screenshot.png"]
dir_path=r"C:/Users/messa/Desktop/Python keylogger/"
##This function to take a screenshot---------------
def takess():
im = ImageGrab.grab()
im.save(dir_path+ "/" + "screenshot.png")
## i have multiple functions tell me if this is not enough .
My solution idea: I tried to check for this path if it does not exist i'll create it, after creating the directory i want to create the files in this directory, but it gives me a permission error " PermissionError: [Errno 13] Permission denied:"
extend = "\\"
dir_path="C:\\Users\\Default\\AppData\\Local"
Path(dir_path).mkdir(parents=True, exist_ok=True)
files = ["log.txt", "info.txt", "clipboard.txt", "screenshot.png"]
for file in files:
f= open(dir_path + extend + file, "w+")
f.close()
You can use pathlib module to get a stored location
import pathlib
dir_path = pathlib.Path().absolute()
I have an annual file located on our netwrok that contains sub-folders based on each week of the year. I am trying to write a script that will copy a "Template" document saved on my desktop, then iterate through the annual file, and paste the Template into each weekly sub-folder.
I have a script that is generating a "PermissionError: [Errno 13] Permission denied:" though I am not sure why, and therefore not sure what to do about it.
import os
import shutil
myPath = r"""K:\PROCESS\YEAR"""
myDocument = r"""C:\Users\me.domain\OneDrive - Co Name\Desktop\Template.xlsx"""
for filename in os.listdir(myPath):
with open(os.path.join(myPath,filename)) as myFile:
copyfile(myDocument, myFile)
Error is,
PermissionError: [Errno 13] Permission denied: ‘K:\PROCESS\YEAR\WEEK 1’
# line 'with open(os.path.join(myPath,filename)) as myFile:'
I tried moving the target document to the program root and modified the script based on some sugestions as seen below.
import os
from shutil import copy2
my_doc_path = "Template.xlsx"
myPath = "K:\PROCESS\YEAR"
for directory in os.listdir(myPath):
copy2(my_doc_path, directory)
I am no longer receiving any errors; however, the target document is not being coppied to the target directory. Instead, a nondescript "file" with the target directory name is being created in the program root as seen in the image below.
What ended up working:
import os
from shutil import copy
my_doc_path = "Template.xlsx"
myPath = "K:\PROCESS\YEAR"
for directory in os.listdir(myPath):
target_directory = myPath + '\\' + directory
check_file = target_directory + '\\' + my_doc_path
if not os.path.exists(check_file):
copy(my_doc_path, target_directory)
Instead of opening a file, try to copy your file in the target folders.
from shutil import copy
my_doc_path = "/here/is/my/doc/path.xlsx"
myPath = "K:\PROCESS\YEAR"
for directory in os.listdir(myPath):
copy(my_doc_path, directory)
Or if you need also the metadata:
from shutil import copy2
my_doc_path = "/here/is/my/doc/path.xlsx"
myPath = "K:\PROCESS\YEAR"
for directory in os.listdir(myPath):
copy2(my_doc_path, directory)
Why copy/copy2 instead of copyfile? take a look at this comment
The document name needed to be appended to myPath variable. I incorrectly assumed the copy2() function was looking for the path to save the document to, I didnt realize it required the full destination path including the document itself.
Thanks for the feedback everyone, it got me pointed in the right direction.
I am trying to open the file from folder and read it but it's not locating it. I am using Python3
Here is my code:
import os
import glob
prefix_path = "C:/Users/mpotd/Documents/GitHub/Python-Sample-
codes/Mayur_Python_code/Question/wx_data/"
target_path = open('MissingPrcpData.txt', 'w')
file_array = [os.path.abspath(f) for f in os.listdir(prefix_path) if
f.endswith('.txt')]
file_array.sort() # file is sorted list
for f_obj in range(len(file_array)):
file = os.path.abspath(file_array[f_obj])
join_file = os.path.join(prefix_path, file) #whole file path
for filename in file_array:
log = open(filename, 'r')#<---- Error is here
Error: FileNotFoundError: [Errno 2] No such file or directory: 'USC00110072.txt'
You are not giving the full path to a file to the open(), just its name - a relative path.
Non-absolute paths specify locations in relation to current working directory (CWD, see os.getcwd).
You would have to either os.path.join() correct directory path to it, or os.chdir() to the directory that the files reside in.
Also, remember that os.path.abspath() can't deduce the full path to a file just by it's name. It will only prefix its input with the path of the current working directory, if the given path is relative.
Looks like you are forgetting to modify the the file_array list. To fix this, change the first loop to this:
file_array = [os.path.join(prefix_path, name) for name in file_array]
Let me reiterate.
This line in your code:
file_array = [os.path.abspath(f) for f in os.listdir(prefix_path) if f.endswith('.txt')]
is wrong. It will not give you a list with correct absolute paths. What you should've done is:
import os
import glob
prefix_path = ("C:/Users/mpotd/Documents/GitHub/Python-Sample-"
"codes/Mayur_Python_code/Question/wx_data/")
target_path = open('MissingPrcpData.txt', 'w')
file_array = [f for f in os.listdir(prefix_path) if f.endswith('.txt')]
file_array.sort() # file is sorted list
file_array = [os.path.join(prefix_path, name) for name in file_array]
for filename in file_array:
log = open(filename, 'r')
You are using relative path where you should be using an absolute one. It's a good idea to use os.path to work with file paths. Easy fix for your code is:
prefix = os.path.abspath(prefix_path)
file_list = [os.path.join(prefix, f) for f in os.listdir(prefix) if f.endswith('.txt')]
Note that there are some other issues with your code:
In python you can do for thing in things. You did for thing in range(len(things)) it's much less readable and unnecessary.
You should use context managers when you open a file. Read more here.
I've something like this in my program:
A main script main.py inside a folder named 'OpenFileinaModule'. There's a folder called 'sub' inside it with a script called subScript.py and a file xlFile.xlsx, which is opened by subScript.py.
OpenFileinaModule/
main.py
sub/
__init__.py (empty)
subScript.py
xlFile.xlsx
Here is the code:
sub.Script.py:
import os, openpyxl
class Oop:
def __init__(self):
__file__='xlFile.xlsx'
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
print os.path.join(__location__, __file__)
self.wrkb = openpyxl.load_workbook(os.path.join(__location__,
__file__),read_only=True)
main.py:
import sub.subScript
objt=sub.subScript.Oop()
When I execute main.py, I get the error:
IOError: [Errno 2] No such file or directory: 'C:\\Users\\...\\OpenFileInaModule\\xlFile.xlsx'
It jumps the sub folder...
I've tried
__file__='sub/xlFile.xlsx'
But then the "sub" folder is duplicated:
IOError: [Errno 2] No such file or directory: 'C:\\Users\\...\\OpenFileInaModule\\sub\\sub/xlFile.xlsx'
How to open xlFile.xlsx with subScript.py from main.py?
you're overriding __file__ with __file='xlFile.xlsx', do you mean to do this?
I think you want something like
import os
fname = 'xlFile.xlsx'
this_file = os.path.abspath(__file__)
this_dir = os.path.dirname(this_file)
wanted_file = os.path.join(this_dir, fname)
I'd suggest always using the absolute path for a file, especially if you're on windows when a relative path might not make sense if the file is on a different drive (I actually have no idea what it would do if you asked it for a relative path between devices).
Please avoid using __file__ and __location__ to name your variables, these are more like builtin variables which might cause a confusion.
Note something here:
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
You have not included sub directory and the above joins only the CWD + os.path.dirname(__file__). This doesn't get you to the file. Please read the documentation of os.path.dirname: os.path.dirname(__file__) returns an empty string here.
def __init__(self):
file = 'xlFile.xlsx'
location = os.path.join('sub', file)
location = os.path.abspath(location) # absolute path to file
location = os.path.realpath(location) # rm symbolic links in path
self.wrkb = openpyxl.load_workbook(location)
Probably a very noob question..
But
When I try:
f = open(os.path.join(os.path.dirname(__file__), filename),"w")
I get an error
IOError: [Errno 2] No such file or directory: '/home/path/filename'
Isnt it that since i have said "w" .. it will write a new file if its not there already?
The error message can be reproduced like this:
import os
filename = '/home/path/filename'
f = open(os.path.join(os.path.dirname(__file__), filename),"w")
f.close()
# IOError: [Errno 2] No such file or directory: '/home/path/filename'
The problem here is that filename is an absolute path, so
os.path.join ignores the first argument and returns filename:
In [20]: filename = '/home/path/filename'
In [21]: os.path.join(os.path.dirname(__file__), filename)
Out[21]: '/home/path/filename'
Thus, you are specifying not only a file that does not exist, you are specifying a directory that does not exist. open refuses to create the directory.
Are you trying to literally write home/path/filename? In that case, it's complaining that /home/path doesn't exist. Try creating a directory named /home/path or choosing a file name inside a directory that already exists (for example, find out what the path is to your actual home directory.) You can also use relative paths. See
http://en.wikipedia.org/wiki/Path_%28computing%29
for the difference between absolute and relative paths.