Python relative path or placeholder - python

I coded simple code to import merge filter calculate dataframe, but I can use only on my computer. How can I make it usable on any computer, via relative path or a placeholder?
Code for import dataframe is down, and code working only on my machine because file path is hard-coded, I need a solution how to code this to search .xlsx on desktop for example.
katalog_CJM = pd.read_excel(
r"C:\Users\adise\Desktop\Catalogue - 20.07.-09.08.2022 - EXAMPLE\10.Katalog_Katalog_CJM_20.07.2022-09.08.2022.xlsx",
sheet_name='Katalog')
Another code for export I need to save on any desktop or documents in windows:
Venera_merge.to_excel(
r"C:\Users\adise\Desktop\Catalogue - 20.07.-09.08.2022 - EXAMPLE\EXPORT PO DOBAVLJACIMA- PROGRAM\Venera.xlsx",
index=False)
Thanks to all

From following code you will get path same as %UserProfile% and then you can concatenate further path for desktop.
import os
os.environ['USERPROFILE']
Output:
C:\\User\\user_name

Related

How can I import a csv from another folder in python?

I have a script in python, I want to import a csv from another folder. how can I do this? (for example, my .py is in a folder and I want to reach the data from the desktop)
First of all, you need to understand how relative and absolute paths work.
I write an example using relative paths. I have two folders in desktop called scripts which includes python files and csvs which includes csv files. So, the code would be:
df = pd.read_csv('../csvs/file.csv)
The path means:
.. (previous folder, in this case, desktop folder).
/csvs (csvs folder).
/file.csv (the csv file).
If you are on Windows:
Right-click on the file on your desktop, and go to its properties.
You should see a Location: tag that has a structure similar to this: C:\Users\<user_name>\Desktop
Then you can define the file path as a variable in Python as:
file_path = r'C:\Users\<your_user_name>\Desktop\<your_file_name>.csv'
To read it:
df = pd.read_csv(file_path)
Obviously, always try to use relative paths instead of absolute paths like this in your code. Investing some time into learning the Pathlib module would greatly help you.

Python searching for image in wrong directory

I am trying to load some assets onto my program that I have them in a folder called 'Graphics', which is inside the folder 'Snake', which is inside the folder 'Projects', which is inside the folder 'Python'. However, also inside that folder 'Python' is another folder named 'HelloWorld'.
I am trying to load some assets in a program that I am running in 'Snake' and Python is searching for the assets in the 'HelloWorld' folder (which is where I used to keep my python files).
I get the error:
FileNotFoundError: No file 'Projects/Snake/Graphics/apple.png' found in working directory 'C:\Users\35192\OneDrive - WC\Desktop\Python\HelloWorld'
I believe that for this I have to change the default directory for vs code. I have changed the default directory for the command prompt and it did nothing. Perhaps this is because the python that I am running in the command prompt is different from the one in vs code (?)
How do I fix this?
Thank you in advance.
Edit:
This is how I am currently loading the image:
apple = pygame.image.load('Projects\Snake\Graphics\apple.png').convert_alpha()
Use pathlib to construct the path to your images. You wil have to add import pathlib to your code.
pathlib.Path(__file__) will give you the path to the current file. pathlib.Path(__file__).parent will give you the folder. Now you can construct the path with the / operator.
Try the following code and check the output.
import pathlib
print(pathlib.Path(__file__))
print(pathlib.Path(__file__).parent)
print(pathlib.Path(__file__).parent / 'Grahics' / 'apple.png')
Now you will be able to move the full project to a totally different folder without having to adjust any code.
Your code example looks like this: apple = pygame.image.load('Projects\Snake\Graphics\apple.png').convert_alpha()
If you import pathlib you can replace that with the dynamic approach:
path_to_image= pathlib.Path(__file__).parent / 'Grahics' / 'apple.png'
apple = pygame.image.load(path_to_image).convert_alpha()
I'm quite sure that pygame can work with a path from pathlib. If not then you have to convert the path to a string manually
apple = pygame.image.load(str(path_to_image)).convert_alpha()
You don't need to change the default directory. Just load from the full directory. That should look something like: "C:\Users\...\Python\Snake\Graphics\apple.png".
I think the simplest way is to first see your active directory by simply typing in
pwd, and then you could simply change the directory by cd("C:/path/to/location"), remember you have to use the backslash, or just use the following library:
import os
os.chdir("C:/path/to/location")
As pydragon posted, you could also import it by just giving the import function a path.

Python: Excel file (xlsx) export with variable as the file path, using pandas

I defined an .xlsx file path as the variable output:
print(output)
r'C:\Users\Kev\Documents\Python code.xlsx'
I want to export a pandas dataframe as an .xlxs file, but need to have the file path as the output variable.
I can get the code to work with the file path. I've tried about a dozen ways (copying and/or piecing code together from documentation, stack overflow, blogs, etc.) and getting a variety of errors. None worked. Here is one that worked with the file path:
df = pd.DataFrame(file_list)
df.to_excel(r'C:\Users\Kev\Documents\Python code.xlsx', index=False)
I would want something like:
df.to_excel(output, index=False)
In any form or package, as long as it produces the same xlsx file and won’t need to be edited to change the file path and name (that would be done where the variable output is defined.
I've attempted several iterations on the XlsxWriter site, the openpyxl site, the pandas site, etc.
(with the appropriate python packages). Working in Jupyter Notebook, Python 3.8.
Any resources, packages, or code that will help me to use a variable in place of a file path for an xlsx export from a pandas dataframe?
Why I want it like this is a long story, but basically I'll have several places at the top of the code where myself and other (inexperienced) coders can quickly put file paths in and search for keywords (rather than hunt through code to find where to replace paths). The data itself is file paths that I'll iteratively search through (this is the beginning of a larger project).
try to put the path this way
output = "C://Users//Kev//Documents//Python code.xlsx"
df.to_excel(output , index=False)
Always worked for me
or you can also do like
output = "C://Users//Kev//Documents//"
df.to_excel(output +"Python code.xlsx" , index=False)
os module would be the most useful here:
from os import path
output = path.abspath("your_excel_file.xlsx")
print(output)
this will return the current working directory path plus the file name you've put into the abspath function as a parameter. Also for those interested about why some people use backslash "\" and not forwardslash "/" while writing file paths here is a good stackoverflow answer for it So what IS the right direction of the path's slash (/ or \) under Windows?
You can use format strings with python3
import pandas as pd
df = pd.DataFrame({"a":"b"}, {"c": "d"})
file_name = "filename.xlsx"
df.to_excel(f"/your/path/to/file/{file_name}", index=False)
Assuming that OP's dataframe is df, that OP is using Windows and wants to store the file in the Desktop, OP's username is cowboykevin05, and the filename that one wants is 0001.xlsx, one can use os.path as follows
from os import path
df.to_excel(path.join('C:\\Users\\cowboykevin05\\Desktop', '0001.xlsx'), index=False)

From dataframe to Excel in Desktop

I exported dataframe from Python to Excel. I have no problem, but I have a question if someone can help me. Can I change the path of the file without having to go through personal folders like "crisf" in my case, to save it to the desktop? I am looking for a generic route that can be applied to all computers
xlwriter= pd.ExcelWriter(r'C:\Users\crisf\Desktop\OHH + GIT + M3.xls')
I doubt that all computers will have user called "crisf". Instead use this and get universal path (path contains user’s home directory):
import os
***some code
xlwriter= pd.ExcelWriter(os.path.expanduser("~/Desktop") + path of folder on desktop + file name)
I run print(os.path.expanduser("~\Desktop")) command on my PC and got:
C:\Users\korne\Desktop

cannot write file with full path in Python

This is a problem that has been previously solved (cannot write file with full path in Python) however I followed the advice in the previous answer and it didn't work and that's why I'm posting this.
I'm trying to access a csv file to load into the pandas dataframe.
import os
output_path = os.path.join('Desktop/My_project_folder', 'train.csv')
This is returning:
IOError: File Desktop/My_project_folder/train.csv does not exist
edit: I don't understand because the train.csv file exists in my project folder.
The os.path.join() function is platform agnostic meaning it can run across multiple OS (PC, Mac, Linux) without having the need to specify directories or subdirectories with forward or back slashes. Hence, simply separate paths and file names by commas:
myDir = '/path/to/Desktop/My_project_folder'
output_path = os.path.join(myDir, 'train.csv')
However, if Python script resides in same directory as data, have script detect its own path and then import data frame into pandas and avoiding hard-coding whole path names:
import os
import pandas as pd
# SET CURRENT DIRECTORY
cd = os.path.dirname(os.path.abspath(__file__))
traindf = read_csv(os.path.join(cd, 'train.csv'))

Categories

Resources