How do I read in a file that has a line of text but I need to iterate inside each element? The file needs to be accessed inside the script beyond the scope of the "with" statement.
For example, file.txt contains the single line "abcdefg" without the quotes. If I write the code below, it doesn't work as I believe I'm creating a single element inside the list (i.e. 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'm assuming this creates a single element of "abcdefg" inside lines which of course won't 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)
This does work. I guess my real question is, is there a better way to accomplish this? It seems like a roundabout method to make it a list and THEN a string. I suppose I could just import it directly to a string and skip making it a list all together. I just would like to know if I could do want I want with it as a list?
It seems like what you're looking for is .read(), not .readlines(). .readlines returns an array of lines. You want the entire file as a string, thus .read().
file = 'file.txt'
with open(file) as file_object:
content = file_object.read()
for letter in content:
if letter == "a":
print(letter)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With