I need to translate chunks of matlab code into Python. My code seems to be 'unreachable' though. Any idea why this is happening? Also: am I doing it right? I'm a real newbie.
Matlab code:
function Dir = getScriptDir()
fullPath = mfilename('fullpath');
[Dir, ~,~] = fileparts(fullPath);
end
function [list,listSize] = getFileList(Dir)
DirResult = dir( Dir );
list = DirResult(~[DirResult.isdir]); % select files
listSize = size(list);
end
My Python code:
def Dir = getScriptDir():
return os.path.dirname(os.path.realpath(__file__)
def getFileList(Dir):
list = os.listdir(Dir)
listSize = len(list)
getFileList() = [list, listSize]
3 Answers 3
Your syntax is incorrect. If I'm reading this correctly, you're trying to get the names of the files in the same directory as the script and print the number of files in that list.
Here's an example of how you might do this (based on the program you gave):
import os
def getFileList(directory = os.path.dirname(os.path.realpath(__file__))):
list = os.listdir(directory)
listSize = len(list)
return [list, listSize]
print(getFileList())
Output example:
[['program.py', 'data', 'syntax.py'], 3]
2 Comments
Your function definitions were incorrect. I have modified the code you provided. You can also consolidate the getScriptDir() functionality into the getFileList() function.
import os
def getFileList():
dir = os.path.dirname(os.path.realpath(__file__))
list = os.listdir(dir)
listSize = len(list)
fileList = [list, listSize]
return fileList
print(getFileList())
Returns: (in my environment)
[['test.py', 'test.txt', 'test2.py', 'test2.txt', 'test3.py', 'test4.py', 'testlog.txt', '__pycache__'], 8]
Your script functions - including getScriptDir(modified):
import os
def getScriptDir():
return os.path.dirname(os.path.realpath(__file__))
def getFileList(dir):
dir = os.path.dirname(os.path.realpath(__file__))
list = os.listdir(dir)
listSize = len(list)
fileList = [list, listSize]
return fileList
dir = getScriptDir()
print(getFileList(dir))
Comments
Remember that you need to return variables from a python-function to get their results.
More on how to define your own functions in python: https://docs.python.org/3/tutorial/controlflow.html#defining-functions
getFileList() = [list, listSize]does not seems like correct code. Maybereturn [list, listSize]? Also, using camelCase named functions is violates python code standart