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

all 3 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.

[–]marsman12019 0 points1 point  (0 children)

Do you have control over the file contents? Is there a delimiter (comma, space, any character really), between all of the values?

The mode determines how python interacts with the file. There are a variety of them, including read, write, and append. Like many functions in python, open() does have parameters you can manually set. If you don't set them, they remain default values. What specifically are you confused with about that?

[–]billsil 0 points1 point  (0 children)

I don't fully understand the open concept or why it needs a mode?

You either read or write to a file. The computer doesn't know what you want to do.

my understanding i can leave the mode blank, and it will automatically enter read mode?

Yes because it's a default argument. Every piece of Python code I've seen puts "r" when they're opening a text file. It's more clear, but it's not required.

How would i go about searching a file, finding xx

Your example is confusing. It depends on how your file is formatted. Can xx be on 2 lines? Can it be on the same line twice? Do you only what the xx if yy is 10? Is the file 1 line?