0

Each time I start a new Python project, I define a read_file method. Something like:

def read_file(file_name: str) -> List[str]:
    with open(file_name) as f:
        lines = f.readlines()
    return lines

Usually, I also add a write_file method.

Is there a Python package from which I can import a method with the same interface? If there isn't such a package I will create one :)

I want to emphasize that I'm aware of these solutions, but I want this exact interface because it is simpler.

Amit Keinan
  • 178
  • 3
  • 11
  • `pathlib`'s `.read_text()` is the closest built-in thing I can think of, but that returns a string rather than a list of lines. – jasonharper May 12 '23 at 15:13
  • thanks @jaonharper. In addition to the difference in the output, pathlib's solution also requires constructing a `Path` object, which I find redundant for my use case. – Amit Keinan May 12 '23 at 18:45

1 Answers1

0

I don't think it makes sense to make a function for this. It would be more readable and faster to write open(file_name).readlines() instead of read_file(file_name).
Don't worry about this solution not containing a with, read_lines is just as unsafe as open is

Antosser
  • 346
  • 1
  • 9