Reputation: 438
I'm trying to build a keyword tool. For this, I built a python script that when you run it, it outputs a CSV file with the keyword, the ranking, the URL and the date.
I want to run more than one keyword and I want to save the output in different folders.
I created 5 different folders with my python script and I created a bash file that runs the script with different keywords and outputs different CSV files.
The bash file looks like this:
#! /bin/bash
/usr/bin/python3 /kw1/rank.py [website] [keyword1]
sleep 30
/usr/bin/python3 /kw2/rank.py [website] [keyword2]
sleep 20
/usr/bin/python3 /kw3/rank.py [website] [keyword3]
sleep 30
/usr/bin/python3 /kw4/rank.py [website] [keyword4]
sleep 25
/usr/bin/python3 /kw5/rank.py [website] [keyword5]
The problem I am having is that when I run my bash file, all the CSV outputs are stored in the home folder, where the bash file is located and not on the specific folder where the python script.
I tried to add >> and location/output.csv or .txt but the output is in a .txt file or if its in CSV its in one column. Also, this is not my python output, it's only what the terminal outputs when running the python script.
The python code that saves my output to CSV looks like this
file = datetime.date.today().strftime("%d-%m-%Y")+'-' +keyword + '.csv'
with open(file, 'w+') as f:
writer = csv.writer(f)
writer.writerow(['Keyword' , 'Rank', 'URL' , 'Date'])
writer.writerows(zip( d[0::4], d[1::4] , d[2::4], d[3::4]))
I would like to run my bash file on one folder but I want to get my script outputs in the specific folder the python script is located.
Thanks.
Upvotes: 0
Views: 6851
Reputation: 126
Use an absolute path when opening file for writing...
import os.path
# PRETEND YOU 'example' folder under C:\
save_to_path = 'C://example//'
name_of_file = input("What is the name of the file: ")
complete_name = os.path.join(save_to_path, name_of_file+".txt")
with open(complete_name, 'w+') as f:
f.write('Hi')
Now you have Hi.txt file in C:\example\
Upvotes: 2
Reputation: 22601
The file you are opening does not contain a folder, it is just a filename:
file = datetime.date.today().strftime("%d-%m-%Y")+'-' +keyword + '.csv'
Therefore, Python interprets it as a relative path, meaning it adds the current PATH to its beginning.
You most likely run the program from /home/<user>/
, therefore the file ends up in your home directory.
There are multiple ways to deal with that:
Upvotes: 1