Iterating inside a Python list item

How do I read in a file that has a line of text, but I need to iterate inside each element? The file must be accessible inside the script outside of the "with" statement.

For example, file.txt contains the single string "abcdefg" without quotes. If I write the code below it doesn't work as I believe I am creating one item inside the list (ie Lines = ['abcdefg']:

file = 'file.txt'
with open(file) as file_object:
    lines = file_object.readlines()
for letter in lines:
     if letter == "a":
         print(letter)

      

I am assuming this creates a single "abcdefg" element within the strings, which of course will not equal "a".

I can get around this by converting the list to a string:

{snip}
text_file_string = ''.join(lines)
for letter in text_file_string:
    if letter == "a":
        print(letter)

      

It works. I guess my real question is, is there a better way to do this? It seems to be a circular method to make it a list and THEN a string. I guess I could just import it straight into a string and skip, making it a list all together. I just would like to know if I might wish I wanted with it as a list?

+3


source to share


4 answers


It seems that you are looking for .read()

, not .readlines()

. .readlines

returns an array of strings. You want the whole file to be a string, so .read()

.



file = 'file.txt'
with open(file) as file_object:
    content = file_object.read()
    for letter in content:
         if letter == "a":
             print(letter)

      

+2


source


Looping through the lines gives you one line at a time. Move down the line to get one character at a time:



file = 'file.txt'
with open(file) as file_object:
    lines = file_object.readlines()
for line in lines:
    for letter in line:
        if letter == "a":
             print(letter)

      

0


source


You need to nest a second loop.

file = 'file.txt'
with open(file) as file_object:
    lines = file_object.readlines()
for line in lines:
    for letter in line:
        if letter == "a":
            print(letter)

      

0


source


Agree with everyone, but with one additional sentence. File objects are iterable. You can make your code simpler by taking advantage of this fact as follows.

with open("myfile.txt", "rt") as file_ob:
    for line in file_ob:
        for letter in line:
            if letter == "a":
                print(letter)

      

0


source







All Articles