0

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)

3 Answers 3

1
import os
if os.path.isfile("trendx.log"):
    pass
    # File exists
else: 
    pass
    # File doesn't exist
Sign up to request clarification or add additional context in comments.

1 Comment

Please some comments or description to explain how your code works.
0

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)

2 Comments

invalid syntax, but this is what im looking for, can your fix your answer so i can accept it
Ahh! There was a issue with using ! vs not. Fixed it
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.