#๐Ÿ”’ Opening & Manipulating Text Files

22 messages ยท Page 1 of 1 (latest)

naive owl
#

I have just completed a main module that converts english text to pig latin. My prof included the readlines method, but I did not include it and I am confused as to why mine still works. Doesn't a file always have to be read?

Here is my solution:

import pig_latin 

def main():
    """Execution begins here."""
    try:
        with open("antony_speech.txt", encoding="utf-8") as f_in:
            try:
                with open("antony_speech_pig_latin.txt", mode="w", encoding="utf-8") as f_out:
                    for line in f_in: # Complete the following for each line 
                        eng_txt = line.rstrip()
                        f_out.write(pig_latin.english_to_pig_latin(eng_txt) + "\n")
            except:
                print(f"Error: File could not be created.")
    except:
        print(f"Error: File could not be opened.")


main()

My prof's solution:


import solution_1  # My Pig Latin module


def main():
    """Execution begins here."""
    in_file = "antony_speech.txt"
    out_file = "antony_speech_pig_latin.txt"
    try:
        with open(in_file, encoding="utf-8") as f_in:
            try:
                with open(out_file, mode="w", encoding="utf-8") as f_out:
                    eng_txt = f_in.readline().rstrip()
                    while eng_txt != "": # Complete the following for each line 
                        f_out.write(solution_1.english_to_pig_latin(eng_txt) + "\n")
                        eng_txt = f_in.readline().rstrip()
            except:
                print(f"Error: File '{out_file}' could not be created.")
    except:
        print(f"Error: Can't open '{in_file}'.")


main()
sharp harborBOT
#

@naive owl

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

pastel hazel
#

File objects are iterable.

#

When you're iterating over a file opened in text mode, by default, it iterates over the lines.

#

Personally, my preference is to use str.splitlines. i.e. py file.read().splitlines()if the file isn't gargantuan so as to preclude holding it all in memory at once.

naive owl
#

ohh I see so there is no need to use read when iterating? But you have to when you don't iterate?

pastel hazel
#

It depends on what suits a given situation.

#

There are often many different ways to come at a problem.

#

One of those ways tends to suit it better, often being the simpler one.

#

When you're not for looping, you'll want to pull data out in some manner, usually.

#

Which means maybe a read or readline call of some sort.

#

Imagine the file handle as like a tape drive with data on it.

#

You know those old fashioned reels?

naive owl
#

Mhm

pastel hazel
#

file.read() reads the whole thing out from the current position, usually the start, to the end.

#

file.readline() will read up to the next line

#

iterating over file will do similar to file.readline

naive owl
#

Ohh I see that makes so much sense now thanks!!

pastel hazel
#

So you could do file.readline() file.readline() file.readline() to get the first three lines, then a file.read() to get the rest in one chunk.

naive owl
#

Mhm makes sense!!

sharp harborBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.