Unable to loop through images in SimpleITK - python

I want to read through images in different folders. I wrote the following code
for Case_id in range(1,6):
path ='/Users/XXXXXX/Desktop/pyradiomics/Converted/Case{}/'.format(Case_id)
print(path)
for files in os.listdir(path):
if files.endswith("Image.nii"):
print(files)
image=sitk.ReadImage (files)
if files.endswith("label.nii"):
print(files)
mask=sitk.ReadImage (files)
When I run this I get an error message:
RuntimeError: Exception thrown in SimpleITK ReadImage:
/scratch/dashboard/SimpleITK-OSX10.6-x86_64-pkg/SimpleITK/Code/IO/src/sitkImageReaderBase.cxx:89:
sitk::ERROR: The file "xxxx_image.nii" does not exist.
If I just run the print command I can see all the files along with path in the specified folder. Would appreciate the help.

#dave-chen is correct. You need to join the path to get the full path.
Try:
for Case_id in range(1,6):
path ='/Users/XXXXXX/Desktop/pyradiomics/Converted/Case{}/'.format(Case_id)
print(path)
for files in os.listdir(path):
if files.endswith("Image.nii"):
print(files)
image=sitk.ReadImage(os.path.join(path, files))
if files.endswith("label.nii"):
print(files)
mask=sitk.ReadImage(os.path.join(path, files))

I'm guessing you need to pass the full path name to ReadImage. 'files' is only the name of the file. If you're not running the script in that 'path' directory, ReadImage won't fine the files, so it's going to look in the current working directory.

Related

For loop with files with Python

I have this code:
import os
directory = "JeuDeDonnees"
for filename in os.listdir(directory):
print("File is: "+filename)
This code run and prints files name in a VSCode/Python environment.
However, when I run it in Sikuli-IDE I got this error:
[error] SyntaxError ( "no viable alternative at input 'for'", )
How can I make this for loop run or is there an alternative that can work?
Answer found ;
Basically, in my Sikuli-IDE environnement, there's layers of Python, Java, Jython... interlocking each other so the Path finding was tedious.
src_file_path = inspect.getfile(lambda: None) #The files we're in
folder = os.path.dirname(src_file_path) # The folder we're in
directory = folder + "\JeuDeDonnees" # Where we wanna go
for filename in os.listdir(directory) # Get the files
print(filename)
We're telling the Path where we are with the current file, get the folder we're in, then moving to "\JeuDeDonnees" and the files.

Getting FileNotFoundError: when I try to read the excel files in my directory

I want to print all the excel files in my Cleaned_Data folder but when I run the code I get:
FileNotFoundError
The code:
directory = r"C:\Users\andre\OneDrive\Desktop\python_web_scrapper\Cleaned_Data"
for filename in os.listdir(directory):
if filename.endswith(".xlsx"):
pd.read_excel(filename)
filename only contains the name of the file and not its entire path. Your script does not see the file since it's looking for it where you are and not in the directory folder. You need to add the path to the file:
import os
directory = r"C:\Users\andre\OneDrive\Desktop\python_web_scrapper\Cleaned_Data"
for filename in os.listdir(directory):
if filename.endswith(".xlsx"):
pd.read_excel(os.path.join(directory, filename))

Python error FileNotFoundError: [Errno 2] No such file or directory:

Im trying to run my code with this but keep running into a file not found error.
files = [i for i in os.listdir('C:/Users/me/Desktop/python data')]
for filename in files:
data = pandas.read_excel(str(filename))
I've tried looking around but cant seem to understand.
Running print(os.getcwd()) does find the file in the folder but i still get the error message
You need to concatenate the path and the filename returned from os.listdir:
PATH = 'C:/Users/me/Desktop/python data'
files = [os.path.join(PATH, i) for i in os.listdir(PATH)]
for filename in files:
data = pandas.read_excel(str(filename))
Further recommendations:
You can use pathlib's .glob to get the full path without using os.path.join.
Also, if you use read_excel, please consider filtering by xls/xlsx files:
Code example:
import pathlib
path = pathlib.Path('C:/Users/me/Desktop/python data')
excel_filter = "*.xls*"
for filename in path.glob(excel_filter):
print(filename)

Recovering filenames from a folder in linux using python

I am trying to use the listdir function from the os module in python to recover a list of filenames from a particular folder.
here's the code:
import os
def rename_file():
# extract filenames from a folder
#for each filename, rename filename
list_of_files = os.listdir("/home/admin-pc/Downloads/prank/prank")
print (list_of_files)
I am getting the following error:
OSError: [Errno 2] No such file or directory:
it seems to give no trouble in windows, where you start your directory structure from the c drive.
how do i modify the code to work in linux?
The code is correct. There should be some error with the path you provided.
You could open a terminal and enter into the folder first. In the terminal, just key in pwd, then you could get the correct path.
Hope that works.
You could modify your function to exclude that error with check of existence of file/directory:
import os
def rename_file():
# extract filenames from a folder
#for each filename, rename filename
path_to_file = "/home/admin-pc/Downloads/prank/prank"
if os.exists(path_to_file):
list_of_files = os.listdir(path_to_file)
print (list_of_files)

os.chdir() giving error with parsing the path

I am getting error while trying to change the Current directory to a different folder in python. My code is as below:
I take PATH_DIR as input from user and the user passes absolute path.
files[]
for directories in os.listdir(PATH_DIR):
files.append(directories)
for dir in files:
abs = os.path.abspath(dir)
print abs
os.chdir(abs)
In my compilation trail I give the PATH_DIR as C:\Python27\Scripts and the directories in this folder are 'WIN7' 'WIN8'. When I execute the program, I get an error as below.
WindowsError: [Error 2] The system cannot find the file specified: 'C:\Python27\Scripts\WIN7'
In principle, the command os.chdir() is some how adding a '\' character before every '\' in the directory path. Can you please help me solve this issue.
os.chdir(abs)
You are trying to cd into FILE.
os.listdir() will return full content of given directory.
You need to check whether entity is a directory with os.path.isdir()
import os
PATH_DIR = '.'
files = []
for directory in os.listdir(PATH_DIR):
print os.path.isdir(os.path.join('.', directory))
if os.path.isdir(os.path.join('.', directory)):
files.append(directory)
print files
for directory in files:
abs_path = os.path.abspath(directory)
print abs_path
os.chdir(abs_path)

Categories

Resources