How can I read a file using Python?
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 ""
What about reading a binary file?
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).
f = open(filePath,"rb")
The 'rb' should read binary in python.
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.
with
close,
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.
binary_data
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?
Thanks for the suggestion @James Derrick . I confirm it works in Mechanical scripting.
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)