unable to read makefile using python

Question:

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

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

Asked By: GreekGod

||

Answers:

Try :

with open("Makefile", "r") as file:
    for line in file.read().splitlines():
        print(line)
Answered By: SWEEPY

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())
Answered By: Barmar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.