How do you open specific text files on python?
<p>I want to open specific lines from an ordinary text file in python. is there anyway to do this? and how?</p>

<p>First lets see how to open a file to write:</p>

<pre><code>f = open(âfilename.txtâ, âwâ)
</code></pre>

<p>Now we have opened a file named filename, in write mode. Write mode is indicated using âwâ. If a file of that particular name is not present then a new file would be created.</p>

<p>It has created an object of that particular file and we can do all our operations on that particular object. Now we have created an object for writing. The command to write is:</p>

<pre><code>text = âHello Pythonâ
f.write(text) ## or f.write(âHello Pythonâ)
</code></pre>

<p>After doing all our required operations, we need to close the file. The command to close the file is as follows:</p>

<pre><code>f.close()
</code></pre>

<p>This will save the file and close it. Now lets see how to read a file.</p>

<pre><code>f = open(âfilename.txtâ, ârâ)
</code></pre>

<p>Same like write, but only the mode is changed to ârâ. Now we have opened a file named filename, in read mode. Read mode is indicated using ârâ. If a file of that particular name is not present then an error will be raised</p>

<pre><code>Traceback (most recent call last):
  File "", line 1, in 
IOError: [Errno 2] No such file or directory: 'filename.txt' 
</code></pre>

<p>If the file is present, then it would create an object of that particular file and we can do all our operations on that particular object. Now we have created an object for reading. The command to read is:</p>

<pre><code>text = f.read()
print text
</code></pre>

<p>All the contents of the file object is now read and stored in the variable text. Text holds the entire contents of the file.</p>

<p>After doing all our required operations, we need to close the file. The command to close the file is as follows:</p>

<pre><code>f.close()
</code></pre>

<p>In the above examples we have opened the file separately and close it separately, there is a better way to do it using with function. The modified code will be</p>

<pre><code>with open(âfilename.txtâ, ârâ) as f:
    text = f.read()
    print text
</code></pre>

<p>When it comes out of the with block it will automatically close the file.</p>

python