Jay Patel
Jay Patel

Reputation: 23

How to run a Python script in a different directory accessing file of current directory(see example explaining issue)

file1  -> "/1/2/3/summer/mango.txt"  
file2  -> "/1/2/3/winter/dates.txt"  
Script -> "/1/Python/fruit.py"  

Problem 1) I am unable to execute fruit.py in summer/winter folder. While it works properly, if i kept the script in a summer/winter folder.

Problem 2) The script required to access *.txt file of directory where i execute it. Here in example, mango.txt or dates.txt.

Here is my code,

#! /usr/bin/python

import glob
import os
import csv
....

for name in glob.glob("*.txt"):
    target_path_1 = os.path.join(os.path.dirname(__file__), name)

txt_file = open(target_path_1,"r")
ipaddr = raw_input("Enter IP address: ")
fname = (name.replace(".txt","_"))+(ipaddr+".csv")
target_path_2 = os.path.join(os.path.dirname(__file__), fname)
csv_file = open(target_path_2,"w")
writer = csv.writer(csv_file)

....               
csv_file.close()
txt_file.close()

Upvotes: 1

Views: 56

Answers (1)

Roman Pavelka
Roman Pavelka

Reputation: 4171

You have both directories accessible like this:

import os

script_dir = os.path.dirname(os.path.realpath(__file__))
my_dir = os.getcwd()

print(script_dir, my_dir)

Result

~ $ python temp/test.py 
/home/roman/temp /home/roman

Upvotes: 1

Related Questions