How can I read a file using Python?

Pernelle Marone-Hitz
Pernelle Marone-Hitz Member, Moderator, Employee Posts: 871
100 Answers 500 Comments 250 Likes First Anniversary
✭✭✭✭

How can I read a file using Python?

Tagged:

Best Answer

  • Pernelle Marone-Hitz
    Pernelle Marone-Hitz Member, Moderator, Employee Posts: 871
    100 Answers 500 Comments 250 Likes First Anniversary
    ✭✭✭✭
    Answer ✓

    The following function can be used:

        def ReadFile(filePath):
            '''
            read the file filePath
            :param filePath: path of file
            :return strFile: string of the file read
            ''' 
            try:
                strFile =""
                # check if file exists, 
                if (filePath and os.path.isfile(filePath)):
                
                    # reads the file
                    f = open(filePath,"r")        
                    strFile = f.read()            
                    f.close()        
                    
                return strFile        
            except:
                ExtAPI.Log.WriteMessage("Error : Exception in ReadFile()")    
                return ""
    

Answers

  • Alok
    Alok Member, Employee Posts: 10
    10 Comments First Anniversary Ansys Employee
    ✭✭✭

    What about reading a binary file?

  • Pernelle Marone-Hitz
    Pernelle Marone-Hitz Member, Moderator, Employee Posts: 871
    100 Answers 500 Comments 250 Likes First Anniversary
    ✭✭✭✭

    Hi @Alok . The function above is to be used in Mechanical. Not sure what sort of binary file you would like to open there. If you want to read a binary result file, you should consider using DPF (Data Processing Framework).

  • M
    M Member, Employee Posts: 241
    50 Answers 100 Comments 100 Likes Second Anniversary
    ✭✭✭✭

    f = open(filePath,"rb")

    The 'rb' should read binary in python.

  • James Derrick
    James Derrick Administrator, Employee Posts: 269
    Ancient Membership 100 Comments 100 Likes 25 Answers
    admin
    edited January 2023

    You should try to use the with syntax where possible when opening files in Python as it reduces the possibility of accidentally leaving out a trailing close,and it's also a lot more concise.

    At least, that is the case in Python 2.7+. The statements discussed so far would look like this in that syntax.

    with open(file_path, 'r') as my_file:
        string_data = my_file.read()
    

    and for a binary file

    with open(file_path, 'rb') as my_file:
        binary_data = my_file.read()
    

    Note binary_data will be a bytes array type! If you want to access the string (assuming it's encoded as a string), you need to decode it. E.g. we can decode it as UTF8, which is a unicode encoding and one of the most common there is.

    string_data = binary_data.decode('utf8')
    

    This syntax is available in Python 2.7, but @Pernelle Marone-Hitz can you confirm if it works in ACT as well?

  • Pernelle Marone-Hitz
    Pernelle Marone-Hitz Member, Moderator, Employee Posts: 871
    100 Answers 500 Comments 250 Likes First Anniversary
    ✭✭✭✭

    Thanks for the suggestion @James Derrick . I confirm it works in Mechanical scripting.

  • Mike.Thompson
    Mike.Thompson Member, Employee Posts: 345
    25 Answers 100 Comments 25 Likes First Anniversary
    ✭✭✭✭
    edited January 2023

    Just to add to this thread the code to write to a file since it is very similar:


    MyText = "Hello World"
    with open(file_path, 'w') as my_file:
        binary_data = my_file.write(MyText)