Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

unable to read makefile using python

I am trying to read the contents of the Makefile using python.

Makefile

# Dev Makefile

SHELL := /bin/bash
platform_ns ?= abc
app_namespace ?= xyz

wftmpl = wftmpl.yaml
wftmpl_name ?= abc.yaml
service_account ?= dev_account
br_local_port = 8000
tr_local_port = 8001
storage_root_path ?= some_location

I used the following code to read the file in python file expocting all the files in the same directory.

python_script.py

with open("Makefile", "r") as file:
    while (line := file.readline().rstrip()):
        print(line)

Expected output

# Dev Makefile

SHELL := /bin/bash
platform_ns ?= abc
app_namespace ?= xyz

wftmpl = wftmpl.yaml
wftmpl_name ?= abc.yaml
service_account ?= dev_account
br_local_port = 8000
tr_local_port = 8001
storage_root_path ?= some_location

Current output

# Dev Makefile

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I need to print all the content of the Makefile using python

>Solution :

The problem is that the while condition is the line after calling rstrip(). If the line is blank, this will be an empty string, and this is falsey, so the loop ends.

You should test the line before stripping it.

while (line := file.readline()):
    print(line.rstrip())

or more simply:

for line in file:
    print(line.rstrip())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading