简体   繁体   中英

Python .txt file iteration and readlines()

I am a bit stuck with reading a file line by line, assigning it to a variable and having the rest of my code applied to this variable. My code is doing exactly what it needs to do, I am just stuck on iterating over the file. I get the "Mixing iteration and read methods would lose data" error when I try:

for line in file:
    user_input = file.readlines()

and doing this way I can only get the last line to be read:

for line in user:
    user_input = line

So how do I want to go about reading each line in the file? I feel like this will be a repeat question but I am just not sure how to go about this.

If you want to iterate over the lines one by one, you do this:

for line in file:
    do_something_with(line)

Your second version isn't working because all you do is reassign the local variable user_input to each line over and over again, so at the end, you just have the last one.

You need to actually do something with the line, right there in the loop. Whether that means process it and write some output, or add it to a list or a dict or some other collection for later, depends on what you're trying to do.

For example, if you were building a set of all the words in the file, you could do this:

words = set()
for line in file:
    words |= set(line.split())

If you want to read the whole file all at once to get a list of all of the lines, on the other hand, you do this:

lines = file.readline()

… or this:

lines = list(file)

If you need to loop over the lines multiple times, or access them in arbitrary order, this can be very useful.

If not, whatever you wanted to do with lines , you could probably just have done directly with file instead, so you're wasting time and memory building that list.


Your code is mixing the two together:

for line in file:
    user_input = file.readline()

In other words, for each line in the file, you're trying to read the whole file. This doesn't make any sense. Either do something with each line, or read the whole file just one time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM