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

First line a of a file not printing in a function

I was looking around but I couldn’t find a question similar that also includes functions.

My PYTHON code is supposed to output every line in a text file, but in uppercase. I understand how you’d do this without functions, but I have to use a function.

It prints out everything in uppercase, but the first line, I think its because of the f.read ?? I’ve played around with it, but then it just outputs nothing. I also tried a different method, but it created an entirely new file, and that’s not the result I need. Any ideas on how to go about this?

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

Here’s what I did


def uppercase():
    with open("qwerty.txt", "r") as f:
        for line in f:
            line = f.read()
            line = line.upper()
        return line


print(uppercase())

>Solution :

You don’t need to do line = f.read() since you’re already getting the line with your loop variable. This is why your program doesn’t output the first line.
Moreover, the return is outside the loop so that means you will only return the last value of line. My guess is that your function should directly print all the lines in uppercase, it’s ok if it returns nothing.
So basically, you should end up with a function like this:

def uppercase(file):
    with open(file, "r") as f:
        for line in f:
            line = line.upper()
            print(line)

uppercase("query.txt")
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