Python on Mac // Changing Working Directory - python

I have been instructed to change the working working directory. We were provided a file and instructed to put in the Documents folder if we were using a Mac. I cannot seem to to get it work.
from pathlib import Path
import os
Path.cwd()
print(os.getcwd())
os.chdir('/Users/VClark/Documents/cpt180Stuff')
Path.cwd()
print(os.getcwd())
This is the error I am getting:
/Users/VClark/Desktop/CPT 180
Traceback (most recent call last):
File "/Users/VClark/Desktop/CPT 180/workWithFiles.py", line 9, in <module>
os.chdir('Users/VClark/Documents/cpt180Stuff')
FileNotFoundError: [Errno 2] No such file or directory: 'Users/VClark/Documents/cpt180Stuff'

When you are dealing with directories, you must always have a "/" at the beginning of the file path, and at the end, indicating the last word is also a folder, or else it will be treated as a file. And you can't change directories to a file. /Users/hussein/Documents/ is good, Users/hussein/Documents/ and /Users/hussein/Documents are not.

Related

OSError: [WinError 87] The parameter is incorrect: 'C:\\Temp1\\Registry\\R2_XML_Files'

I sporadically get this error using Python 3.10 in Windows. I've tried installing 3.7.8 to get around the error (based on prior posts) but it persists.
It can happen with any module, including os. For example, I can perform the command os.chdir() successfully but then when I try os.listdir() I get the error message.
This works:
file_loc = r"C:\Temp1\Registry\R2_XML_Files" # source directory for Registry
os.chdir(file_loc)
But then when I run
os.listdir(file_loc)
The error is
>>> os.listdir(file_loc)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [WinError 87] The parameter is incorrect: 'C:\\Temp1\\Registry\\R2_XML_Files'
I've also tried using the pathlib module to troubleshoot Windows path issues with
file_loc = pathlib.PureWindowsPath ("C:/Temp1/Registry/R2_XML_Files")
but I still get the error
I've also tried not changing the directory but this code also fails:
file_loc = r"C:\Temp1\Registry\R2_XML_Files" # source directory for Registry
os.listdir(file_loc)
>>> os.listdir(file_loc)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [WinError 87] The parameter is incorrect: 'C:\\Temp1\\Registry\\R2_XML_Files'
>>>
On a related note, I've also noticed when using the following code, I get a similar error, but only every 4 days. It runs for 3 days, then throws the same OSError. I can prevent the error by preemptively re-creating (in Windows) the folder "c:/Temp1/Covid"
dir_name = r"c:/Temp1/Covid"
extension = ".zip"
os.chdir(dir_name)
for item in os.listdir(dir_name): # loop through items in dir
if item.endswith(extension): # check for ".zip" extension
file_name = os.path.abspath(item) # get full path of files
zip_ref = zipfile.ZipFile(file_name) # create zipfile object
zip_ref.extractall(dir_name) # extract file to dir
zip_ref.close() # close file
os.remove(file_name)
Is there some Windows metadata that allows Windows to see and rename folders but does not allow Python to do so?
Have also run into the problem trying to pip install some modules.
I work for a hospital and have escalated to IT Security and no one seems to be able to figure out why this is occurring. The error also occurs for my colleagues and it is a huge hassle trying to keep Python stable. Starting over with a new install and new virtual environments sometimes works but sometimes doesn't.
Thanks very much.

Pygame Error : FileNotFoundError: No such file or directory

I'm new to programming and just following the steps provided online to make a small game in pygame to learn.
I recently have a problem when I wanted to add an image.
Here is my code.
#sprite
from turtle import Screen
import pygame
import random
import os
WIDTH=500
HEIGHT=600
#遊戲初始化 and 創建視窗
pygame.init()
screen=pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("spacegame")
background_img=pygame.image.load(os.path.join("img","background.png")).convert()
screen.blit(background_img,(0,0))
The trouble come when I run it, and they say :
Traceback (most recent call last):
File "d:\python\test.py", line 13, in <module>
background_img=pygame.image.load(os.path.join("img","background.png")).convert()
FileNotFoundError: No file 'img\background.png' found in working directory 'D:\img'.
PS D:\img>
You are already in the 'img' directory.
So you can use the following line to get the image:
background_img=pygame.image.load("background.png").convert()
It is not enough to put the files in the same directory or sub directory. You also need to set the working directory. A file path has to be relative to the current working directory. The working directory is possibly different to the directory of the python script.
The name and path of the file can be retrieved with __file__. The current working directory can be get by os.getcwd() and can be changed with os.chdir(path).
Put the following at the beginning of your code to set the working directory to the same as the script's directory:
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))

File not found in working directory pygame

I am attempting to make a simple pygame game, and I need to load in some images. When I run my code, or:
bg_image = pygame.image.load('assets/Fondotiff.tif(1).png').convert_alpha()
It gives me an error which says:
Traceback (most recent call last):
File "C:\Users\victo\Desktop\Assets - Pulga\mainpulga.py", line 12, in <module>
bg_image = pygame.image.load('assets/Fondotiff.tif(1).png').convert_alpha()
FileNotFoundError: No file 'assets/Fondotiff.tif(1).png' found in working directory 'C:\Users\victo\Desktop\Assets - Pulga'.
***Repl Closed***
I have double checked if the image is inside the folder on my desktop and it is there, but for some reason it doesn't find it.
How can I fix this?
The asset file path has to be relative to the current working directory. The working directory is possibly different from the directory of the python file.
It is not enough to put the files in the same directory or sub directory. You also need to set the working directory.
e.g.:
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))

How do I fix visual studio code path error?

so I have this problem in visual code, when I open a file in the same directory of a project, visual code doesn't identify the file unless I give him the whole directory
This is the image of the error:
cwd:
Specifies the current working directory for the debugger, which is the base folder for any relative paths used in code. If omitted, defaults to ${workspaceFolder} (the folder open in VS Code).
And you can set it to:${fileDirname} - the current opened file's dirname(official docs)
Try this way to set working directory manually:
/tmp/1/
/tmp/2/file
import os
print("Current working directory: {0}".format(os.getcwd()))
> Current working directory: /tmp/1
open('file', 'r')
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> FileNotFoundError: [Errno 2] No such file or directory: 'file'
os.chdir('/tmp/2')
open('file', 'r')
> <_io.TextIOWrapper name='file' mode='r' encoding='UTF-8'>
Also you can set directory related to the running python file:
import os
print(os.path.dirname(os.path.abspath(__file__)))
python /tmp/1/file.py
> /tmp/1
The good practice is to set application path somewhere in global configuration file

How to pickle to a different folder on Linux?

When I used Windows, this was my code:
save_documents = open("pickled_algos/documents.pickle", "wb")
pickle.dump(documents, save_documents)
save_documents.close()
And what it did is make a second folder called "pickled_algos" and saved it there. Now I'm using Ubuntu Linux and when I write that same code I get this error:
Traceback (most recent call last):
File "PATH/sentimentProjectSaving.py", line 136, in <module>
save_documents = open("pickled_algos/documents.pickle", "wb")
FileNotFoundError: [Errno 2] No such file or directory: 'pickled_algos/documents.pickle'
How do I do the same thing I did in Windows, but on Linux?
EDIT: When I remove "pickled_algos/" then it works, the again the problem is that is saves into the same folder where the python file is.
One reason could be because you're using a relative path instead of an absolute path. Specifically, your error mentions that the directory can't be found so you should first check if the directory exists.
import os
path = 'your path'
# Create target Directory if doesn't exist
if not os.path.exists(path):
os.makedirs(path)
print("Directory created ")
else:
print("Directory already exists")

Categories

Resources