Import CSV when script and CSV in different folder in Python

Viewed 577

new to python and what I want to do is to import csv files which are in different folders than my python script. It didn't work with direct import so I tried it the following way.

I tried to copy the csv files (to plot data) from another folder into the current working directory of the python script. What I initially did was to create an empty init.py file in the folder from where I wanted to copy the csv files and also created a function script in the same folder which plots the data. On desktop when I call this function by using 'from...import' it works (without having to copy the files) but when I do this on the shared folders (accessed using company VPN), I get an error saying the 'No such file or directory: my_csv_file_name'. This error still exists after copy the python files in the shared directory through the python code.

I have attached the code and would be happy to know, how to solve this issue and also if the logic is correct because idk if in 'files' relative path must go. Thank you !

import os
import shutil

def function_copy(file_name1, file_name2, file_name3):
    path1 = "rel_path\\" + file_name1 # relative path of the csv file given
    path2 = "rel_path\\" + file_name2
    path3 = "rel_path\\" + file_name3
    
    start = "..." # Here absolute path of the python script given

    relative_path1 = os.path.relpath(path1,start) 
    relative_path2 = os.path.relpath(path2,start)
    relative_path3 = os.path.relpath(path3,start)
    
    print(relative_path1 , relative_path2 ,relative_path3) # to print relative path w.r.t the absolute path

    files = [relative_path1, relative_path2, relative_path3]
    for f in files:
        shutil.copy(f, str(start)) # to copy the files from relative path to absolute path of the python script   

function_copy('plot1.csv', 'plot2.csv', 'plot3.csv') # function to run the copy the data in csv files

Blockquote

2 Answers

Use

start = os.getcwd()

to get the absolute path ("current directory") of your python script.

I think it could be because office VPN was blocking the opensource 'Spyder', so that's why it couldn't access the files. Normally the admin has to provide access for it to be donwloaded on the system but in this case it didn't need it.

Related