user8892462
user8892462

Reputation:

Detect first if file is existing before executing the program

How can I check if a file is existing, for example trend.log is existing therefore execute the program, otherwise loop again.

Here is my program, I want to execute if trendx.log is present in my path:

logtext = "trendx.log"
#Log data into dataframe using genfromtxt
logdata = np.genfromtxt(logtext + ".txt",invalid_raise = False,dtype=str, comments=None,usecols=np.arange(16))
logframe = pd.DataFrame(logdata)
#print (logframe.head())

#Dataframe trimmed to use only SHA1, PRG and IP
df2=(logframe[[10,11]]).rename(columns={10:'SHA-1', 11: 'DESC'})
#print (df2.head())

#sha1_vsdt data into dataframe using read_csv
df1=pd.read_csv("sha1_vsdt.csv",delimiter=",",error_bad_lines=False,engine = 'python',quoting=3)
#Using merge to compare the two CSV

df = pd.merge(df1, df2, on='SHA-1', how='left').fillna('undetected')
df1['DESC'] = df['DESC'].values

df1.to_csv("sha1_vsdt.csv",index=False)

Upvotes: 0

Views: 114

Answers (3)

learner
learner

Reputation: 1982

You can use os.path.isfile to check if file exist. You can loop in a while loop till file doesn't exist and execute your code after that loop.

import os

logtext = "trendx.log"
while not os.path.isfile(logtext):
    pass


#Log data into dataframe using genfromtxt
logdata = np.genfromtxt(logtext + ".txt",invalid_raise = False,dtype=str, comments=None,usecols=np.arange(16))
logframe = pd.DataFrame(logdata)
#print (logframe.head())

#Dataframe trimmed to use only SHA1, PRG and IP
df2=(logframe[[10,11]]).rename(columns={10:'SHA-1', 11: 'DESC'})
#print (df2.head())

#sha1_vsdt data into dataframe using read_csv
df1=pd.read_csv("sha1_vsdt.csv",delimiter=",",error_bad_lines=False,engine = 'python',quoting=3)
#Using merge to compare the two CSV

df = pd.merge(df1, df2, on='SHA-1', how='left').fillna('undetected')
df1['DESC'] = df['DESC'].values

df1.to_csv("sha1_vsdt.csv",index=False)

Upvotes: 0

bcollins
bcollins

Reputation: 3449

How about using the os.path module?

from os import path
if path.exists(my_filepath):
    execute_my_program()

You can add a sleep:

from os import path
from time import sleep

def wait_and_process_file(filepath, wait_interval=5, max_time=3600):
    total_time = 0
    while total_time < max_time and not path.exists(filepath):
         sleep(wait_interval)
         total_time += wait_interval

    _finish_processing(filepath)

Upvotes: 0

kpaul
kpaul

Reputation: 375

import os
if os.path.isfile("trendx.log"):
    pass
    # File exists
else: 
    pass
    # File doesn't exist

Upvotes: 1

Related Questions