Home > Blockchain >  Opening python file in different directory in linux
Opening python file in different directory in linux

Time:02-03

I'm attempting to open a file in a different directory than what I am calling my python file from.

I'm also using gitlab-ci when calling my python file as well.

Here is a tree of how it's laid out: Calling python file from root: python3 pyfileloc/file.py

Py file opens a file open.txt to edit in a deeper location:

with open('pyfileloc/deeper/deeper/deeper/open.txt',"r")

I'm wondering how I can access open.txt without using os or any other modules. It is unknown what our root directory is either, so I cannot simply do /pyfileloc/deeper/deeper/deeper/open.txt. I've tried ../deeper/deeper/deeper/open.txt and deeper/deeper/deeper/open.txt and have had no luck.

If I use gitlab ci to cd pyfileloc then python3 file.py would that open me up more options? If I do the cd, do all my future scripts: in gitlab ci run from the cd location and I'd need to cd ../ to get back to root?

I'm new to gitlab-ci and trying to avoid pushing all of my tests to gitlab, and trying to solve this in one answer.

CodePudding user response:

you can use linux by subprocess

import subprocess

data = subprocess.check_output("cat pyfileloc/deeper/deeper/deeper/open.txt".split())

CodePudding user response:

__file__ is always the relative path from the cwd to the running script. You could use that, since you should know the relative path between the running script and the file you want to open.

with open(__file__   "/../deeper/deeper/deeper/open.txt") as f:
    print(f.read())  # or whatever

That said, if you're on a modern version of Python, use pathlib.

import pathlib

path = pathlib.Path(__file__).parent / 'deeper' / 'deeper' / 'deeper' / 'open.txt'

with open(path) as f:
    print(f.read())  # or whatever

CodePudding user response:

I am sorry if i didn't post this as comment but I am new and is an unlocked feature for me.

I understood that you want call this python script in the Gitlab-ci Pipeline and this script need to call a file in a some directory. I just didn't understand if you create this script in the job (or you have it by an artifact for the previous job).

If isn't and you want to call an external script you can mount an additional volume configuring your Runner and achieve that. Only possible if you're using your own Runner and not Shared runner hosted by Gitlab.

https://docs.gitlab.com/runner/configuration/advanced-configuration.html#the-runnersdocker-section

  •  Tags:  
  • Related