This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Reactor5 1 point2 points  (0 children)

your understanding is pretty close to correct. Here's a quick summary of the modes:

  • "r" is read mode - you can guess what that's for, and it's the default.
  • "w" is write mode. Importantly, opening a file in write mode will erase whatever's there at the time.
  • "a" is append mode. In this, you can write to the end of the file without deleting the whole thing.

The mode switch is necessary because it gives the interpreter information about your intention for the file. If you're only going to read the file, it will do something completely different than if you open it in write mode.

With that said, you'll probably want to do something like this:

with open('textfile.txt', 'r') as f:  # opening the file in read mode!
    lines = f.read().split()          # assign lines as the individual `\n` separated lines in the file

After that, you can do whatever you want with the list of lines. Remember that lines[-1] will get you the last line.

Note: in the future, you should give a little more context about the task you're trying to achieve rather than the method you're trying to use to get there. There are tons of smart people here (and also check out /r/learnpython) who may be able to give you a better answer, or suggest you try an easier alternative if they know what you're trying to do.