simple file checking



  • two questions about simplify things in micropython like it is in normal python

    1. How to check if file exists?
      i do not see possibility to check it simple like os.path.isfile
      maybe i do something wrong but i try "all" simple posibilities and finish in this crap of code:
    len([item for item in os.listdir() if fname==item])>0
    
    1. how to check file size?
      i tied this:
    os.stat(fname).st_size 
    

    but it do not understand st_size
    and now i write exact idx like:

    os.stat(fname)[6]


  • @livius Sorry, I did n ot look at the date. I was just surprised that you asked.



  • Hi @robert-hh :)
    I forgot about this very old question and I solved it myself long ago.
    But this can be helpful for the community :)



  • @livius Hi livius,
    since the path methods are not implemente din MP, you cantry to open the file fro reading, and look on whether you run into an execption of not:

    try:
        f = open(fname, "r")
        exists = True
        f.close()
    except FileNotFoundError:
        exists = False
    

    Ans also, since the symbolic element names for os.stat are not implemented, os.stat[6] is the right value, giving the files size in bytes. Also, a check like: os.stat[0] & 0o170000 == 0o040000 will tell you, that the entry is a directory.



  • Checking for file or directory exists using Python

    import os
    dirname = "temp"
    filename = "my_file"
    #check directory exists
    if(os.path.exists(dirname)):
    print("Directory Exists")
    else:
    print("Directory does not exists")
    #check file exists
    if(os.path.exists(filename)):
    print("File Exists")
    else:
    print("File does not exists")

    Full source...file exist


Log in to reply
 

Pycom on Twitter