I am currently using pandas to read an "output.csv" file by specifying the filepath as :
df = pd.read_csv(r'C:\users\user1\desktop\project\output.csv')
While this works perfectly fine on my local machine, is there a way I can code this so anyone who runs the script can use it? I want to be able to hand this script to coworkers who have no knowledge of Python and have them be able to run it without manually changing the username in the path.
I have tried using os.path to no avail:
df = pd.read_csv(os.path.dirname('output.csv'))
CodePudding user response:
If you're shipping out the output.csv
in the same directory as the python script, you should be able to reference it directly pd.read_csv('output.csv')
.
If your need to get the full path filename for the file, you should use os.path.abspath(__file__)
.
Finally, if your output.csv is in a static location in all your coworkers computers and you need to get the username, you can use os.getlogin()
and add it to the path.
So there's a bunch of solutions here depending on your exact problem.
CodePudding user response:
Use this line to get an absolute directory path of your application, then contact your csv file to it.
import os
abspath = os.path.dirname(os.path.realpath(__file__))
print(abspath)
csvpath = abspath '/my_csv_file.csv'
print(csvpath)