Pycharm throws FileNotFoundError after refactor for some file [duplicate] - python-3.x

Recently, I'm unable to use relative paths in my code while using PyCharm. For instance, a simple open('test.txt', 'r') will not work - whereupon I am sure the file exists in the same level as the running py file. PyCharm will return this error.
FileNotFoundError: [Errno 2] No such file or directory:
After reading answers online on StackOverflow, I have tried multiple options including:
Changing test.txt to ./test.txt
Closing project, deleting the .idea folder, open the folder with code.
Reinstalling as well as installing the latest version of PyCharm.
Invalidating caches and restarting.
None of these options have worked for me. Is there someway I can tell PyCharm to refresh the current working directory (or even to see where it thinks the current working directory is)?
Edit: I should note that running the script in a terminal window will work. This appears to be a problem with PyCharm and not the script.

Change:
Run > Edit Configurations > Working directory,
which sets the working directory for a specific project. (This is on a Mac)

I have Pycharm 4.5, so things might have changed a bit.
Try going to Settings > Project > Project Structure
On this dialog, click your folder that has the source code in it, and then click the blue folder in the menu to note it as "source" folder. I believe this fixes a lot of the path issues in Pycharm
Here is the link to "content roots": https://www.jetbrains.com/pycharm/help/content-root.html

Current version 2019.2 somehow ignores "source root" from the "project structure". Here's how to actually enforce it:
Run -> Edit Configurations -> Python -> "Edit Templates" -> fill out "Working Directory"

__file__ refers to file path. So you can use the following to refer file in the same directory:
import os
dirpath = os.path.dirname(__file__)
filepath = os.path.join(dirpath, 'test.txt')
open(filepath, 'r')

In PyCharm, click on "run/edit configurations..."
Then find your script file in the "Python" dropdown menu. Check the "Working Directory" entry and change it if necessary.

EXACT ANSWER TO SOLVE THIS ISSUE ,,
GO TO EDIT CONFIGURATION (just LEFT side of GREEN CODE RUNNER ICON)
click on python (not any specific python script) ONLY SELECT PYTHON
then below right side click on [edit configuration templetes]
select current working dir by going into those blocks
It will change the CWD of all python file that exists in project folder..
then all file will understand the RELATIVE PATH that starts from your actual project name..
i hope this will resolve all your issue related path.

Sometimes it is different. I solved my problem by clicking "Run" at the Pycharm's toolbar and then "Edit Configurations..." and I change my Interpreter to another actual one. Just changing it in the settings does not help, but this opperation already does ;)

I too had the same issue few minutes ago...but,with the latest version of PyCharm it is resolved by simply using the relative path of that file..
For instance, a simple f = open('test', 'r') will work.

A little clarification for mac users. In mac, what #andere said above is correct for setting working directory. However, if your code is in a different folder, say working_dir/src/ (like classic java/scala file structure) in that case you still need to set your Sources Root. In mac's PyCharm this can be done by right clicking on the src/ folder > Mark Directory as > Sources Root. Helped me with lot of similar import issues. Hope this helps someone.

Related

'hello world' PyInstaller .app doesn't open

This is a common problem, though the solutions seem diverse and none have helped me.
Like this question and this question, on mac, my PyInstaller .app fails to open when clicked on in Finder. However it does work when launched from the terminal ./helloWorldTest.app/Contents/MacOS/helloWorldTest. The .exe file does works when clicked on in Finder (which from my reading also seems common).
Unlike the apps in the linked questions, my app does not read or write any files: I have entirely gutted my actual app (which has the same problematic behaviour) to a simple hello world version:
# This is a trivial app with a loop to ensure it stays open long enough to actually see something happen before the script finishes.
print('hello world!')
i = 0
while i < 1000000:
print('hello world number: ', i)
i += 1
While >90% of the solutions to similar sounding problems all involve changing paths, that can't be the issue here as there is essentially nothing to this app. So, can anyone help me get this basic app working so I can build & debug from there?
Here is the PyInstaller command I use: pyinstaller helloWorldTest.py --onefile --icon=dipyIcon.icns -w --clean
Kinda surprising got given how seemingly prevalent this issue is. Anyway, for anyone searching/googling this in the future, hopefully this will help.
The issue is caused by the default version of something called Tcl that is used in your bundled app. The latest version for some reason doesn't work, so you need to manually set it to a slightly older version.
Note: This solution was found by manuelf23, I am only relaying it here. You can find the original thread here
To do this:
Right click your .app file (the one with the icon, you have given it one)
Click Show package contents (You're now in the hidden files that are bundled together. These files sit in a standard OSX structure, which is the same architecture as any app on a mac
Navigate to this file: ./Contents/Resources/tcl/init.tc [note, you do not use the --onefile flag otherwise you'll only have your icon in the Resources folder]
Open the init.tc file in any text editor and go to line 19
On line 19 you'll find this line (package require -exact Tcl 8.6.8) and replace it with package require -exact Tcl 8.5.9 - or put simply change the Tcl version to 8.5.9
Et Voilà, vous êtes au top- go back to your app and double click your icon
Just in case, here's the PyInstaller command I used:
pyinstaller myFileName.py -w --icon myIconName.icns
EDIT: forgot to link source of solution

Unresolved import error - Python virtual-environment [duplicate]

I am using the following setup
macOS v10.14 (Mojave)
Python 3.7.1
Visual Studio Code 1.30
Pylint 2.2.2
Django 2.1.4
I want to use linting to make my life a bit easier in Visual Studio Code. However, for every import I have states "unresolved import". Even on default Django imports (i.e. from django.db import models).
I presume it is because it is not seeing the virtual environment Python files.
Everything works just fine, but it's starting to get annoying.
The interpreter choices I have are all system versions of Python. It does not seem to see my virtual environment Python at all (it is not in the same directory as my workspace, so that part makes sense).
If I set up the python.PythonPath in the settings.json file, it just ignores it and does not list my virtual environment path as an option. I also tried setting it up in my global Python settings, but it also does not show up.
Is there a quick fix to get it working?
The accepted answer won't fix the error when importing own modules.
Use the following setting in your workspace settings .vscode/settings.json:
"python.autoComplete.extraPaths": ["./path-to-your-code"],
Reference: Troubleshooting, Unresolved import warnings
In your workspace settings, you can set your Python path like this:
{
"python.defaultInterpreterPath": "/path/to/your/venv/bin/python",
}
Alternative way: use the command interface!
Cmd/Ctrl + Shift + P → Python: Select Interpreter → choose the one with the packages you look for:
This issue has already been opened on GitHub:
Python unresolved import issue #3840
There are two very useful answers, by MagnuesBrzenk and SpenHouet.
The best solution for now is to create a .env file in your project root folder. Then add a PYTHONPATH to it like this:
PYTHONPATH=YOUR/MODULES/PATH
And in your settings.json add:
"python.envFile": ".env"
When I do > reload window that fixes it.
Reference: Python unresolved import issue #3840, dkavraal's comment
None of the solutions worked except this one. Replacing "Pylance" or "Microsoft" in the settings.json solved mine.
"python.languageServer": "Jedi"
You need to select the interpreter associated with the virtual environment.
Click here (at the bottom status bar):
And just select the virtual environment you are working with. Done.
Sometimes, even with the interpreter selected, it won't work. Just repeat the process again and it should solve it.
If you have this code in your settings.json file, delete it:
{
"python.jediEnabled": false
}
If you are more visual like myself, you can use the Visual Studio Code configurations in menu File → Preferences → Settings (Ctrl + ,). Go to Extensions → Python.
In the section Analysis: Disabled, add the suppression of the following message: unresolved-import:
I was able to resolved this by enabling jedi in .vscode\settings.json
"python.jediEnabled": true
Reference from https://github.com/Microsoft/vscode-python/issues/3840#issuecomment-456017675
I wonder how many solutions this problem have (or have not), I tried most of the above, nothing worked, the only solution that worked is to set the python language server to Jedi, instead of Microsoft in the settings.json file:
"python.languageServer": "Jedi"
None of the previous answers worked for me. Adding both of the lines below to my settings.json file did, however.
"python.analysis.disabled": [
"unresolved-import"
],
"python.linting.pylintArgs": ["--load-plugin","pylint_protobuf"]
The first line really just hides the linting error. Certainly not a permanent solution, but de-clutters the screen.
This answer gave me the second line: VS Code PyLint Error E0602 (undefined variable) with ProtoBuf compiled Python Structure
Maybe someone who understands Python more than me can explain that one more.
Okay, so 2 years down the line, I have ran into this annoying problem. All I can seen here are some really complicated workarounds. Here are easy to follow steps for anyone else who might just run into this later on:
at the bottom of VS Code where you see the Python version listed, just click there
Select Interpreter windows is going to appear
click on the first option that says "Select Interpreter Path" and navigate to the folder path which has your Virtual Environment
That's all you need to do and avoid tampering with those settings in VS Code which might get very complicated if not handled with caution.
My solution
This solution is only for the current project.
In the project root, create folder .vscode
Then create the file .vscode/settings.json
In the file setting.json, add the line (this is for Python 3)
{
"python.pythonPath": "/usr/local/bin/python3",
}
This is the example for Python 2
{
"python.pythonPath": "/usr/local/bin/python",
}
If you don't know where your Python installation is located, just run the command which python or which python3 on the terminal. It will print the Python location.
This example works for dockerized Python - Django.
I was facing the same problem while importing the project-related(non standard) modules.
Detailed explanation of the problem
Directory structure:
Project_dir:
.vscode/settings.json
dir_1
> a
> b
> c
dir_2
> x
> y
> z
What we want:
Project_dir
dir_3
import a
import y
Here "import a" and "import y" fails with following error:
Import "dir_1.a" could not be resolvedPylancereportMissingImports
Import "dir_2.y" could not be resolvedPylancereportMissingImports
What worked for me:
Appending the top directory which contains the modules to be imported.
In above example add the follwoing "Code to append" in ".vscode/settings.json"
Filename:
.vscode/settings.json
Code to append:
"python.analysis.extraPaths": [dir_1, dir_2]
The solution from Shinebayar G worked, but this other one is a little bit more elegant:
Copied from Python unresolved import issue #3840:
Given the following example project structure:
workspaceRootFolder
.vscode
... other folders
codeFolder
What I did to resolve this issue:
Go into the workspace folder (here workspaceRootFolder) and create a .env file
In this empty .env file, add the line PYTHONPATH=codeFolder (replace codeFolder with your folder name)
Add "python.envFile": "${workspaceFolder}/.env" to the settings.json
Restart Visual Studio Code
To me the problem was related with the project that I was working on. It took me a while to figure it out, so I hope this helps:
Original folder structure:
root/
__init__.py # Empty
folder/
__init__.py # Empty
sub_folder_b/
my_code.py
sub_folder_c/
another_code.py
In another_code.py:
from folder.sub_folder_b import my_code.py
This didn't trigger the intellisense in Visual Studio Code, but it did execute OK.
On the other hand, adding "root" on the import path, did make the intellisense work, but raised ModuleNotFoundError when executing:
from root.folder.sub_folder_b import my_code.py
The solution was to remove the _init_.py file inside the "folder" directory, leaving only the _init_.py located at /root.
This works for me:
Open the command palette (Ctrl + Shift + P) and choose "Python: Select Interpreter".
Doing this, you set the Python interpreter in Visual Studio Code.
None of the answers here solved this error for me. Code would run, but I could not jump directly to function definitions. It was only for certain local packages. For one thing, python.jediEnabled is no longer a valid option. I did two things, but I am not sure the first was necessary:
Download Pylance extension, change python.languageServer to "Pylance"
Add "python.analysis.extraPaths": [ "path_to/src_file" ]
Apparently the root and src will be checked for local packages, but others must be added here.
I am using the following setup: (in Apr 2021)
macos big sur
vscode
Anaconda 3 (for environment)
And I faced this error during starting of the Django.
So, I follow these steps and this error is resolved.
Steps are given in these screenshots:
Open settings (workspace)
Follow this screenshot to open Python Path
Now, click Edit in settings.json
Make path like given in this screenshot /opt/anaconda3/bin/python
5. Now, save this settings.json file.
6. Restart the vscode
Also, intellisense might not work for some time hold on wait for some time and then restart again then vscode reads file for new path.
That happens because Visual Studio Code considers your current folder as the main folder, instead of considering the actual main folder.
The quick way to fix is it provide the interpreter path to the main folder.
Press Command + Shift + P (or Ctrl + Shift + P on most other systems).
Type Python interpreter
Select the path where you installed Python in from the options available.
Changing
Python:Language Server
to 'Jedi' worked for me.
It was 'Windows' initially.
For me, it worked, if I setup the paths for python, pylint and autopep8 to the local environment paths.
For your workspace add/change this:
"python.pythonPath": "...\\your_path\\.venv\\Scripts\\python.exe",
"python.linting.pylintPath": "...\\your_path\\.venv\\Scripts\\pylint.exe",
"python.formatting.autopep8Path": "...\\your_path\\.venv\\Scripts\\autopep8.exe",
Save and restart VS Code with workspace.
Done!
I have a different solution: my Visual Studio Code instance had picked up the virtualenv stored in .venv, but it was using the wrong Python binary. It was using .venv/bin/python3.7; using the switcher in the blue status bar.
I changed it to use .venv/bin/python and all of my imports were resolved correctly.
I don't know what Visual Studio Code is doing behind the scenes when I do this, nor do I understand why this was causing my problem, but for me this was a slightly simpler solution than editing my workspace settings.
In case of a Pylint error, install the following
pipenv install pylint-django
Then create a file, .pylintrc, in the root folder and write the following
load-plugins=pylint-django
I have faced this problem in three ways. Although for each of them a solution is available in the answers to this question, I just thought to put it all together.
First I got an "Unresolved Import" while importing some modules and I noticed that my installations were happening in global pip instead of the virtual environment.
This issue was because of the Python interpreter. You need to select the interpreter in Visual Studio Code using Shift + Ctrl + P and then type Select Python Interpreter. Select your venv interpreter here.
The second issue was: The above change did not resolve my issue completely. This time it was because of file settings.json. If you don't have the settings.json file in your project directory, create one and add the following line in that:
{
"python.pythonPath": "apis/bin/python"
}
This will basically tell Visual Studio Code to use the Python interpreter that is in your venv.
The third issue was while importing a custom Python module or file in another program. For this you need to understand the folder structure. As Python in venv is inside bin, you'll need to specify the folder of your module (most of the time the application folder). In my case it was app,
from app.models import setup_db
Verbally, import setup_db from models.py resides in the app folder.
If you are using pipenv then you need to specify the path to your virtual environment.in settings.json file.
For example :
{
"python.pythonPath":
"/Users/username/.local/share/virtualenvs/Your-Virual-Env/bin/python"
}
This can help.
If someone happens to be as moronic as me, the following worked.
Old folder structure:
awesome_code.py
__init__.py
src/
__init__.py
stuff1.py
stuff2.py
New structure:
awesome_code.py
src/
__init__.py
stuff1.py
stuff2.py
How to avoid warning
Please note that this is just skipping the warning not resolving it.
First of all open visual studio code settings in json and add following arguments after "[python]":{}
"python.linting.pylintArgs": ["--rep[![enter image description here][1]][1]orts", "12", "--disable", "I0011"],
"python.linting.flake8Args": ["--ignore=E24,W504", "--verbose"]
"python.linting.pydocstyleArgs": ["--ignore=D400", "--ignore=D4"]
This has helped me to avoid pylint warnings in VSCode.
I have resolved import error by Ctrl + Shift + P.
Type "Preferences settings" and select the option Preferences Open Settings (JSON)
And add the line "python.pythonPath": "/usr/bin/"
So the JSON content should look like:
{
"python.pythonPath": "/usr/bin/"
}
Keep other configuration lines if they are present.
This should import all modules that you have installed using PIP for autocomplete.

Cannot Find the Correct Working Directory in Python Spyder

I'm having trouble with the working directory in Spyder console. I'm trying to convert an xlsx file into a pandas array, but I keep getting the same error. I've changed the Run Directory in preferences and it should be the correct one.
screenshot of Spyder console
Sorry if this is a really newbie question I just really dont know where to go from here.
The path at the top right of the screen in Spyder will change the working directory of the IPython console. Set it to the desired working directory. Hit Ctrl+F6 to check the run configuration of your script and make sure it is set to run at the current work directory. See if that fixes the problem.
As others have mentioned, the os module provides a way of getting and changing the working directory directly through python, rather than changing the working directory settings in Spyder. Your second option is to do the following before importing the .xlsx file:
import os
os.chdir('C:/Users/mypath') # Change your working directory to your .xlsx file location
The other useful os function to check what your current directory is:
os.getcwd()
As for your current case, there isn't any issue. The runfile('', wdir='') text is simply letting you know which .py script you are running and for what working directory. There isn't any other output, because you haven't set anything to happen after you read the excel file to xls_file. Try adding a print(xls_file) statement to the end of your script and it should print the pandas DataFrame to the console.
(Spyder maintainer here) There's no error after you change your directory in the Run menu. runfile is the function used by Spyder to run a file in the IPython console. You are simply not getting any output after runfile because you're not printing anything. If you add the command print(xls_file) at the last line of your file, then you'll see the output.
You can always read a file giving the full path. From read_excel doc.
excelSheet = pd.read_excel(io="C://..//myfile.csv")

PyCharm does not find pygame [duplicate]

I've downloaded pygame-1.9.1release.tar.gz from the Pygame website. I extracted and installed it and it's working fine in the command line Python interpreter in Terminal (Ubuntu). But I want to install it for some IDE, like PyCharm. How can I do it?
Well, you don't have to download it for PyCharm here. You probably know how it checks your code. Through the interpreter! You don't need to use complex command lines or anything like that. You need to is:
Download the appropriate interpreter with PyGame included
Open your PyCharm IDE (Make sure it is up to date)
Go to File
Press Settings (Or Ctrl + Alt + S)
Double click on the option that looks like Project: Name_of_Project
Click on Project Interpreter
Choose the interpreter you want to use that includes PyGame as a module
Save your options
And you are ready to go! Here is an alternate (I have never done this, please try to test it)
Add PyGame in the same folder as your PyCharm file (Your PyCharm stuff is always in
a specific file placed by you during installation/upgrade)
Please consider putting your PyCharm stuff inside a folder for easy access.
I hope this helps you!
For PyCharm 2017 do the following:
File - Settings
Double click on your project name
Select Project Interpreter
Click on green + button on the right side of the window
Type Pygame in search window
Click Install package.
Not I'm saying that the answers above won't work, but it might be frustrating to a newbie to do command line magic.
If you are using PyCharm and you are on a Windows 10 machine use the following instructions:
Click on the Windows start menu and type cmd and click on the Command Prompt icon.
Use the command pushd to navigate to your PyCharm project which should be located in your user folder on the C:\ drive. Example: C:\Users\username\PycharmProjects\project name\venv\Scripts.
(If you are unsure go to the settings within PyCharm and navigate to the Python Interpreter settings. This should show you the file path for the interpreter that your project is using. Credit to Anthony Pham for instructions to navigate to interpreter settings.)
HINT: Use copy and paste in the command prompt to paste in the file path.
Use the command pip install pygame and the pip program will handle the rest for you.
Restart you Pycharm and you should now be able to import pygame
Hope this helps. I had a fun time trying to find out the correct way to get it installed, so hopefully this helps someone out in the future.
I just figured it out!
Put the .whl file in C:\Program Files\Anaconda3
While in the folder, click on the blue File tab in the upper left corner of the Window Explorer (assuming you're using Windows)
Click on Open Windows PowerShell as administrator
Write or just copy and paste: py -m pip install pygame
It should start installing
Done!
I hope it works for you. I know it did for me.
I already had pygame installed with python38-32
since its working just fine with it. I used this version of python us my project interpreter.
1.File -settings
2.according to your settings look for project interpreter
3.click on your current project interpreter and click on the add symbol
4.choose system interpreter
5.select the python version thats works with pygame for you
6.Note: some versions of pygame don't work with some versions of python be sure
of what are you doing.
7.hope it works.

Loading R libraries [duplicate]

I am running R on Windows, not as an administrator. When I install a package, the following command doesn't work:
> install.packages("zoo")
Installing package(s) into ‘C:/Program Files/R/R-2.15.2/library’
(as ‘lib’ is unspecified)
Warning in install.packages :
'lib = "C:/Program Files/R/R-2.15.2/library"' is not writable
To install a package, I have to specify a library location:
install.packages("zoo", lib="C:/software/Rpackages")
To load a package, I also have to specify the library location:
library("zoo", lib.loc="C:/software/Rpackages")
All of this is OK, but I wanted to see if I could add C:/software/Rpackages to the library path somehow and thus not have to type it each time.
As I searched online, I found that one way to do this is to edit the Rprofile.site file and to add the line
.libPaths("C:/software/Rpackages")
However, after doing this, and starting RStudio, this is the output that I get
> .libPaths()
[1] "C:/Program Files/R/R-2.15.2/library" "C:/Program Files/RStudio/R/library"
The .libPaths command that I added to the Rprofile.site doesn't seem to have had any effect! Why is this the case? Or more importantly, how can I fix the problem so that I can install and load packages without typing in the library location?
Note: if I start RStudio the .libPaths() command seems to work as it is supposed to
.libPaths("C:/software/Rpackages")
> .libPaths()
[1] "C:/software/Rpackages" "C:/Program Files/R/R-2.15.2/library"
Isn't that strange?
The proper solution is to set environment variable R_LIBS_USER to the value of the file path to your desired library folder as opposed to getting RStudio to recognize a Rprofile.site file.
To set environment variable R_LIBS_USER in Windows, go to the Control Panel (System Properties -> Advanced system properties -> Environment Variables -> User Variables) to a desired value (the path to your library folder), e.g.
Variable name: R_LIBS_USER
Variable value: C:/software/Rpackages
If for some reason you do not have access to the control panel, you can try running rundll32 sysdm.cpl,EditEnvironmentVariables from the command line on Windows and add the environment variable from there.
Setting R_LIBS_USER will ensure that the library shows up first in .libPaths() regardless of starting RStudio directly or by right-clicking an file and "Open With" to start RStudio.
The Rprofile solution can work if RStudio is always started by clicking the RStudio shortcut. In this case, setting the default working directory to the directory that houses your Rprofile will be sufficient. The Rprofile solution does not work when clicking on a file to start RStudio because that changes the working directory away from the default working directory.
I generally try to keep all of my packages in one library, but if you want to add a library why not append the new library (which must already exist in your filesystem) to the existing library path?
.libPaths( c( .libPaths(), "~/userLibrary") )
# obviously this would need to be a valid file directory in your OS
# min just happened to be on a Mac that day
Or (and this will make the userLibrary the first place to put new packages):
.libPaths( c( "~/userLibrary" , .libPaths() ) )
Then I get (at least back when I wrote this originally):
> .libPaths()
[1] "/Library/Frameworks/R.framework/Versions/2.15/Resources/library"
[2] "/Users/user_name/userLibrary"
The .libPaths function is a bit different than most other nongraphics functions. It works via side-effect. The functions Sys.getenv and Sys.setenv that report and alter the R environment variables have been split apart but .libPaths can either report or alter its target.
The information about the R startup process can be read at ?Startup help page and there is RStudio material at: https://support.rstudio.com/hc/en-us/articles/200549016-Customizing-RStudio
In your case it appears that RStudio is not respecting the Rprofile.site settings or perhaps is overriding them by reading an .Rprofile setting from one of the RStudio defaults. It should also be mentioned that the result from this operation also appends the contents of calls to .Library and .Library.site, which is further reason why an RStudio- (or any other IDE or network installed-) hosted R might exhibit different behavior.
Since Sys.getenv() returns the current system environment for the R process, you can see the library and other paths with:
Sys.getenv()[ grep("LIB|PATH", names(Sys.getenv())) ]
The two that matter for storing and accessing packages are (now different on a Linux box):
R_LIBS_SITE /usr/local/lib/R/site-library:/usr/lib/R/site-library:/usr/lib/R/library
R_LIBS_USER /home/david/R/x86_64-pc-linux-gnu-library/3.5.1/
I managed to solve the problem by placing the code in the .Rprofile file in the default working directory.
First, I found the location of the default working directory
> getwd()
[1] "C:/Users/me/Documents"
Then I used a text editor to write a simple .Rprofile file with the following line in it
.libPaths("C:/software/Rpackages")
Finally, when I start R and run .libPaths() I get the desired output:
> .libPaths()
[1] "C:/software/Rpackages" "C:/Program Files/R/R-2.15.2/library"
[3] "C:/Program Files/RStudio/R/library"
https://superuser.com/questions/749283/change-rstudio-library-path-at-home-directory
Edit ~/.Renviron
R_LIBS_USER=/some/path
I found what I think is a solution here (thank you Carl Schwarz at SFU) for adding a personal library that is permanently (you don't have to define it each session) recognized whether using R or Rstudio, and Rstudio treats it as the default on my Mac machine. I hadn't seen it laid out this explicitly on SO, so I summarized the steps they provided, for Windows and then for Mac.
For a Windows 7 OS:
Create a directory on the drive where you want to have your personal library, e.g. C:\User\Rlibs (or another that you have permissions to)
Search for/go to "Edit environment variable for your account" in the Windows search bar to edit control panel settings
Click "New..." in the middle of the "Environmental Variables" window
In the "New User Variable" window, type R_LIBS for the "Variable name", and the path to the personal library directory you created, e.g. C:\User\Rlibs
Click OK and you should see the Variable/Value pair in the User variables window
Click OK again
Now when you start R (or Rstudio) and type the command .libPaths() you should see the personal library you created as well as the R system library.
For Mac:
In your "Home" or "username" directory create a folder called Rlibs
Launch the Terminal application
Type: echo "R_LIBS=~/Rlibs" > .Renviron Make sure the spelling and case matches.
Type ls -a to see the full list of files in the directory, which should now include .Renvrion
Verify that the .Renviron file has been set properly: more .Renviron
Launch R/Rstudio and type .libPaths() and you should see the new path to your personal library.
If you do not have admin-rights, it can also be helpful to open the Rprofile.site-file located in \R-3.1.0\etc and add:
.First <- function(){
.libPaths("your path here")
}
This evaluates the .libPath() command directly at start
just change the default folder for your R libraries in a directory with no Administrator rights, e.g.
.libPaths("C:/R/libs")
On Ubuntu, the recommended way of changing the default library path for a user, is to set the R_LIBS_USER variable in the ~/.Renviron file.
touch ~/.Renviron
echo "R_LIBS_USER=/custom/path/in/absolute/form" >> ~/.Renviron
I've had real trouble understanding this. gorkypl gave the correct solution above when I last re-installed my OS & Rstudio but this time round, setting my environment variable didn't resolve.
Uninstallled both R and Rstudio, creating directories C:\R and C:\Rstudio then reinstalled both.
Define R_LIBS_USER user variable to your prefered directory (as per gorkypl's answer) and restart your machine for User variable to be loaded. Open Rstudio, errors should be gone.
You can also use Sys.setenv() to modify R_LIBS_USER to the path of your alternative library which is easier and does not need to restart your computer.
To see what R_LIBS_USER is set to:
?Sys.getenv()
Reading help(Startup) is useful.
If your default package library has been changed after installing a new version of R or by any other means, you can append both the libraries to use all the packages with the help of the commands below.
Get the existing library path :
.libPaths()
Now,set the existing and the old path :
.libPaths(c(.libPaths(), "~/yourOldPath"))
Hope it helps.
I read the readme. In that they mentioned use .libPaths() in command line to check which paths are there. I had 2 library paths earlier. When I used the command .libpath("C:/Program Files/R/R-3.2.4revised/library") where I wanted, it changed the library path. When I typed in .libPaths() at the command line again it showed me the correct path. Hope this helps
getwd()
# [1] "C:/Users/..../software/My R studio"
copy the above link with double inverted comma
.libPaths(new="C:/Users/..../software/My R studio")
Your default path will change for installing pakages
If you want to change your library path permanently (without calling .libPath() every time when entering in R, this works for me:
create .Rprofile under your home directory. (~/.Rprofile)
type
.libPaths(c( .libPaths(), "your new path" ))
in .Rprofile file, save.
open R (any directory) and check, just type .libPaths(), you can find your libaray path is updated!
Since most of the answers here are related to Windows & Mac OS, (and considering that I also struggled with this) I decided to post the process that helped me solve this problem on my Arch Linux setup.
Step 1:
Do a global search of your system (e.g. ANGRYSearch) for the term Renviron (which is the configuration file where the settings for the user libraries are set).
It should return only two results at the following directory paths:
/etc/R/
/usr/lib/R/etc/
NOTE: The Renviron config files stored at 1 & 2 (above) are hot-linked to each other (which means changes made to one file will automatically be applied [ in the same form / structure ] to the other file when the file being edited is saved - [ you also need sudo rights for saving the file post-edit ] ).
Step 2:
Navigate into the 1st directory path ( /etc/R/ ) and open the Renviron file with your favourite text editor.
Once inside the Renviron file search for the R_LIBS_USER tag and update the text in the curly braces section to your desired directory path.
EXAMPLE:
... Change From ( original entry ):
R_LIBS_USER=${R_LIBS_USER-'~/R/x86_64-pc-linux-gnu-library/4.0'}
... Change To ( your desired entry ):
R_LIBS_USER=${R_LIBS_USER-'~/Apps/R/rUserLibs'}
Step 3:
Save the Renviron file you've just edited ... DONE !!
I had the same problem and I run into this. If you want to create another location c("C:/Users/mynewlocation") should be working as well. As mentioned in here "You should be able to right-click on the Rstudio.exe icon, click Properties, and select an option to always run Rstudio as administrator. Be sure you use that same icon whenever you want to open Rstudio."
myPaths <- .libPaths() # get the paths
myPaths <- c(myPaths[2], myPaths[1]) # switch them
.libPaths(myPaths) # reassign them
I was looking into this because R was having issues installing into the default location and was instead just putting the packages into the temp folder. It turned out to be the latest update for Mcaffee Endpoint Security which apparently has issues with R. You can disable the threat protection while you install the packages and it will work properly.

Resources