0

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

0

2 Answers 2

3

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())
Sign up to request clarification or add additional context in comments.

Comments

1

Try :

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

1 Comment

Or simply: for line in file:

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.