Hello! I am trying to set a line of a text file to a variable
<p>I used an if statement to see if the variable assignment worked but I think I am formatting something wrong. I tried this with and without the \n. Any help would be greatly appreciated.</p>

<pre><code>lines=[] #creates a list
file = open("gmail.txt", "r") #opens the text file
for line in file: 
    lines.append(line) #adds each line to list
file.close()
x=lines[0] #sets first item in list equal to x
print(x)
if x=="Hey \n":    #if statement attempt to check if variable assignment worked
    print("good!")
else:
    print("bad")
</code></pre>

<p>When running the code I get the following output</p>

<pre><code>Hey

bad
</code></pre>

<p>Since the if else statement returned "bad" then I must not understand how the string is formatted when pulling from a line. Any help would be greatly appreciated. </p>

<p>The text file contains</p>

<pre><code>Hey
yo 
</code></pre>

<p>I think you're asking about how to read from a file. Here's the Pythonic way:</p>

<pre><code>with open('gmail.txt') as f:
    for line in f:
        print(line)
</code></pre>

<p>If you want to save all the lines of the file into a list of lines:</p>

<pre><code>with open('gmail.txt') as f:
    lines = f.readlines()
</code></pre>

<p>A more generic way to create a list from something you were for-looping over is to use the <code>list</code> constructor. Here's an example.</p>

<pre><code>with open('gmail.txt') as f:
    lines = list(f)
</code></pre>

python text-files