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?
source to share
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)
source to share