Reputation: 195
I have a python script that will do 3 things:
Right now if I run the script it runs through all 3 functions, regardless of if the file exists in the test directory.
What I want it to do is check to see if the file exists. If it does, copy it, and once it's copied execute the other script. I am having trouble figuring out a simple way to link them all together. Here is my script:
import os
import os.path
from os import path
import shutil
def check_file():
file_exists = False
for deploy_file in os.listdir("C:\\test1\\test.txt"):
if deploy_file.startswith("test"):
file_exists = True
else:
exit(1)
print file_exists
def copy_file():
src = "C:\\test1\\"
dst = "C:\\test2\\"
files = [i for i in os.listdir(src) if i.startswith("test") and path.isfile(path.join(src, i))]
print files
for f in files:
shutil.copy(path.join(src, f), dst)
def run_script():
os.system("pathofscript") # for testing its just a script that prints "hello world"
def main():
check_file()
copy_file()
run_script()
main()
So by running this as-is the output will be:
True
['test.txt']
"hello world"
How can I write my main()
method to do what I am trying to do?
Upvotes: 1
Views: 66
Reputation: 981
You can verify if the file exists with an if statement then run the other two functions. You will have to update check_file()
to return True or False
def check_file():
file_exists = False
for deploy_file in os.listdir("C:\\test1\\test.txt"):
if deploy_file.startswith("test"):
file_exists = True
else:
file_exists = False
return file_exists
Then you can use this as your main function
def main():
if check_file():
copy_file()
run_script()
else:
exit(1)
Upvotes: 1