I'm a Mac user. I'm trying to load a .gpx file on python,using the following code:
import gpxpy
import gpxpy.gpx
gpx_file = open('Downloads/UAQjXL9WRKY.gpx', 'r')
And I get the following message:
FileNotFoundError: [Errno 2] No such file or directory: 'Downloads/UAQjXL9WRKY.gpx'
Could someone help me figure out why? Thanks in advance.
Obviously, one reason would be that the file does not, in fact, exist, but let us assume that it does.
A relative filename (i.e, one that does not start with a /) is interpreted relative to the current working direcory of the process. You are apparently expecting that to be the user's home directory, and you are apparently wrong.
One way around this would be to explicitly add the user's home directory to the filename:
import os
home = os.path.expanduser('~')
absfn = os.path.join(home, 'Downloads/whatever.gpx')
gpx_file = open(absfn, ...)
Related
Issue: Unable to save file in directory (/root/Notion/Image) when using Cron schedule
This is what my code is trying to do:
Check email
Download image attachment
Store in a directory - root/Notion/Image
Retrieve file path
The script is working when I run it manually in Google Cloud terminal. The problem is when I try to schedule it on Cron, it's unable to access the folder to save the file locally.
This is the error when the script failed and require permission:
Traceback (most recent call last):
File "Notion/test.py", line 121, in <module>
path = get_attachments(email.message_from_bytes(msg[0][1]))
File "Notion/test.py", line 47, in get_attachments
with open(filePath, 'wb') as f:
PermissionError: [Errno 13] Permission denied: '/root/Notion/Image/3.jpeg'
This is the code to retrieve attachment from email
def get_attachments(msg):
for part in msg.walk():
if part.get_content_maintype()=='multipart':
continue
if part.get('Content-Disposition') is None:
continue
fileName = part.get_filename()
if bool(fileName):
filePath = os.path.join(attachment_dir, fileName)
with open(filePath, 'wb') as f:
f.write(part.get_payload(decode=True))
return str(filePath)
Resolved:
The problem is that I shouldn't use root directory since it requires permission. I've changed it to home directory instead.
attachment_dir = '/home/dev_thomas_yang/folder_name/folder_name'
For people who needs to check their home direction, simply run this script.
from pathlib import Path
home= str(Path.home())
print(home)
Thanks Triplee for the patience to breakdown my issue despite my sloppy ways of presenting it!
The easiest fix hands down is to change the code so it doesn't try to write to /root. Have it write to the invoking user's home directory instead.
Your question doesn't show the relevant parts of the code, but just change attachment_dir so it's not an absolute path. Maybe separately take care of creating the directory if it doesn't already exist.
import pathlib
# ...
attachment_dir = pathlib.Path("cron/whatever/attachments").mkdir(parents=True, exist_ok=True)
# ...
for loop in circumstances:
get_attachments(something)
A better design altogether would be to have get_attachments accept the directory name as a parameter, so you can make this configurable from the code which calls it. Global variables are a nuisance and cause hard-to-debug problems because they hide information which is important for understanding the code, and tricky to change when you try to debug that code and don't know which parts of the code depend on the old value.
So, I'm making a Python application which has a login system, and it saves the (encrypted) username and password in data/security/logininfo.txt. Here's my code:
import os
os.chdir("data")
os.chdir("security")
info = open("logininfo.txt", "r")
But it keeps giving me this error (the folders data and security exist already):
Traceback (most recent call last):
File "/Users/Me/Desktop/Project/main.py", line 2, in <module>
os.chdir("data")
FileNotFoundError: [Errno 2] No such file or directory: 'data'
How can I fix this?
You are able to open the file by changing your code to the following:
with open('./data/security/logninfo.txt', 'r') as c:
info = c
You can try to check where Python is actually looking to. First of all you can print(os.getcwd()) and check if it corresponds to the directory you think is correct.
Description
Python method chdir() changes the current working directory to the given path.It returns None in all the cases.
Syntax
Following is the syntax for chdir() method −
os.chdir(path)
Parameters
path − This is complete path of the directory to be changed to a new location.
path = str(os.getcwd()) + "/data"
os.chdir( path )
I have to create a empty text file called file.txt under this path
/home/project/test*/today/file.txt
test* changes each time like test_product or test_1 etc..
I tried the following code:
if(os.path.exists("/home/project/test*/today/file.txt"):
print "Found"
else:
open("/home/project/test*/today/file.txt",a).close()```
I got this error
```IOError: [Errno 2] No such file or directory: '/home/project/test*/today/file.txt'```
I understand I can use glob to search the files with paths like * , but I am unable to figure out how to create a file while having * in the path.
Your code logically doesn't make any sense. What you're basically saying is
if the file exists: display the text Found
otherwise the file does not exist, so try to open the file that does not exist
I'll tell you why it doesn't work. os module does not support wildcards.
If you wanted to use wildcards * you could use glob.
import glob
import os
from pathlib import Path
def check_for_files(filepath):
for filepath_object in glob.glob(filepath):
if os.path.isfile(filepath_object):
return True
return False
file_to_check = "/home/project/test*/today/file.txt"
if not (check_for_files(file_to_check):
Path(file_to_check).touch()
I am trying to read content of a file on my work network from my work network. I copy and pasted a code snippet from a google search and modified it to the below. Why might I still be getting [Errno 2] (I have changed some of the path names for this question board)
The file path in my file explorer shows that "> This PC > word common common" and I don't have "This PC" in my path. I tried adding that into the place I would think it goes in the string. That didn't solve it.
I tried making sure I have matching capitalization. That didn't solve it.
I tried renaming the file to have a *.txt on the end. That didn't solve it.
I tried the different variations of // and / and \ with and without the r predecessor and while that did eliminate the first error I was getting. It didn't help this error.
(Looking at the code errors in the right gutter is says my line length is greater than the PEP8 standard. While I doubt that is the root of my problem, if you can throw in the 'right' wrap method for a file path that long that would be helpful.)
myfile = open("z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246", "rt") # open lorem.txt for reading text
contents = myfile.read() # read the entire file into a string
myfile.close() # close the file
print(contents) # print contents
Full Error Copy:
C:\Users\e087680\PycharmProjects\FailureCompiling\venv\Scripts\python.exe C:/Users/e087680/PycharmProjects/FailureCompiling/FirstScriptAttempt.py
Traceback (most recent call last):
File "C:/Users/e087680/PycharmProjects/FailureCompiling/FirstScriptAttempt.py", line 1, in
myfile = open("z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246", "rt") # open lorem.txt for reading text
FileNotFoundError: [Errno 2] No such file or directory: 'z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246'
EDIT
DEBUG EFFORTS
working to figure out how to change directory. Just in case that is the problem. Tested this code bit
import os
path = "z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246"
os.chdir(path)
isExist = os.path.exists(path)
print(isExist)
Received this error
C:\Users\e087680\PycharmProjects\FailureCompiling\venv\Scripts\python.exe C:/Users/e087680/PycharmProjects/FailureCompiling/ScriptDebugJunkFile.py
Traceback (most recent call last):
File "C:/Users/e087680/PycharmProjects/FailureCompiling/ScriptDebugJunkFile.py", line 5, in <module>
os.chdir(path)
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246'
My intention for adding the picture below is to show how File Explorer displays the file path for my file
FileExplorerPathScreenShot
EDIT
I think this confirms that my 'OS' doesn't have my file.
from os import path
path.exists("PCC_ESS_FC_Full_Report_65000122-1_R0016_962019_9246")
def main():
print ("File exists:" + str(path.exists('PCC_ESS_FC_Full_Report_65000122-1_R0016_962019_9246')))
if __name__== "__main__":
main()
Output
File exists: False
I thought OS was a standard variable for Operating system. Now I'm not sure.
EDIT
Using Cmd in DOS, I confirmed that my path for the z: is correct
EDIT - Success
I ran
import os
print( os.listdir("z:/"))
Confirmed I don't need the monster string of folders.
Confirmed, although explorer doesn't show it, it is a *.txt file
Once I implemented these two items the first code worked fine.
Thank you #Furas
To open and read a file specify the filename in your path:
myfile = open("U:/matrix_neo/word common common/hello world.txt", "rt") # open file
contents = myfile.read() # read the entire file into a string
myfile.close() # close the file
print(contents) # print contents
The U: is a mapped drive in my network.
I did not find any issue with your change dir example. I used a path on my U: path again and it returned True.
import os
path = "U:/matrix_neo/word common common"
os.chdir(path)
isExist = os.path.exists(path)
print(isExist)
The check the attributes on the directory that you are trying to read from. Also try to copy the file to a local drive for a test and see if you can read the file and also check if it exists.
This is an alternative to the above and uses your path to make sure that the long file path works:
import os
mypath = "z:/abcdefg/abc123_proj2/word_general/word common common/Users/Mariee/Python/abc_abc_ab_Full_Report_12345-1_R9999_962019_9246"
myfile = 'whatever is your filename.txt'
if not os.path.isdir(mypath):
os.makedirs (mypath)
file_path = os.path.join(mypath, myfile)
print(file_path)
if os.path.exists(file_path) is True:
with open(file_path) as filein:
contents = filein.read()
print(contents)
I tested this code using a long csv file.,Replace the variable myfile with whatever is your file name.
I'm trying to rename an audio file but I keep getting OSError: [Errno 2] No such file or directory.
In my program, each user has a directory that holds the users files. I obtain the path for each user by doing the following:
current_user_path = os.path.join(current_app.config['UPLOAD_FOLDER'], user.username)
/Users/johnsmith/Documents/pythonprojects/project/files/john
Now I want to obtain the path for the existing file I want to rename:
current_file_path = os.path.join(current_user_path,form.currentTitle.data)
/Users/johnsmith/Documents/pythonprojects/project/files/john/File1
The path for the rename file will be:
new_file_path = os.path.join(current_user_path, form.newTitle.data)
/Users/johnsmith/Documents/pythonprojects/project/files/john/One
Now I'm just running the rename command:
os.rename(current_file_path, new_file_path)
you can use os.rename for rename single file.
to avoid
OSError: [Errno 2] No such file or directory.
check if file exist or not.
here is the working example:
import os
src = "D:/test/Untitled003.wav"
dst = "D:/test/Audio001.wav"
if os.path.isfile(src):
os.rename(src, dst)
If the OS says there's no such file or directory, that's the gospel truth. You're making a lot of assumptions about where the file is, constructing a path to it, and renaming it. It's a safe bet there's no such file as the one named by current_file_path, or no directory to new_file_path.
Try os.stat(current_file_path), and similarly double-check the new file path with os.stat(os.posixpath.dirname(new_file_path)). Once you've got them right, os.rename will work if you've got permissions.
Try changing the current working directory to the one you want to work with. This code below should give you a simple walk through of how you should go about it:
import os
print (os.getcwd())
os.chdir(r"D:\Python\Example")
print (os.getcwd())
print ("start")
def rename_files():
file_list= os.listdir(r"D:\Python\Example")
print(file_list)
for file_name in file_list:
os.rename(file_name,file_name.translate(None,"0123456789")) rename_files()
print("stop")
print (os.getcwd())