You can open files with the open function , which lives in the io module but is automatically imported for you.
>>> f = open('somefile.txt')
You can specify full path to the file and some other optional arguments. In case that you are trying to open file, that doesn't exist, you will receive exception like this:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'somefile.txt'
If you use open with only a file name as a parameter, you get a file object you can read from. If you want to write to the file, you must state that explicitly, supplying a mode.
Value | Description |
---|---|
'r' | Read mode (default) |
'w' | Write mode |
'x' | Exclusive write mode |
'a' | Append mode |
'b' | Binary mode |
't' | Text mode |
'+' | Read/write mode |
The default mode is 'rt', which means your file is treated as encoded Unicode text.
Reading and writing
>>> f = open('somefile.txt', 'w')
>>> f.write('Hello, ')
7
>>> f.write('World!')
6
>>> f.close()
Partial reading
>>> f = open('somefile.txt', 'r')
>>> f.read(4)
'Hell'
>>> f.read()
'o, World!'
Reading from stdin
somefile.txt file with text:
Welcome to this file
There is nothing here except
This stupid haiku
somescript.py
import sys
text = sys.stdin.read()
words = text.split()
wordcount = len(words)
print('Wordcount:', wordcount)
Command:
cat somefile.txt | python somescript.py
Wordcount: 12
>>> f = open(r'somefile.txt', 'w')
>>> f.write('01234567890123456789')
20
>>> f.seek(5)
5
>>> f.write('Hello, World!')
13
>>> f.close()
>>> f = open(r'somefile.txt')
>>> f.read()
'01234Hello, World!89'
The method tell() returns the current file position.
>>> f = open(r'somefile.txt')
>>> f.read(3)
'012'
>>> f.read(2)
'34'
>>> f.tell()
5
You should always close files before you exit the script.
You can use try, finally:
# Open your file here
try:
# Write data to your file
finally:
file.close()
with open("somefile.txt") as somefile:
do_something(somefile)
The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks.
In addition, it will automatically close the file. The with statement provides a way for ensuring that a clean-up is always used.
Without with statement
file = open("welcome.txt")
data = file.read()
print data
file.close() # It's important to close the file when you're done with it
With with statement
with open("welcome.txt") as file: # Use file to refer to the file object
data = file.read()
do something with data
Let's use our somefile.txt.
read(n)
>>> f = open(r'somefile.txt')
>>> f.read(7)
'Welcome'
>>> f.read(4)
' to '
>>> f.close()
read()
>>> f = open(r'somefile.txt')
>>> print(f.read())
Welcome to this file
There is nothing here except
This stupid haiku
>>> f.close()
readline()
>>> f = open(r'somefile.txt')
>>> for i in range(3):
print(str(i) + ': ' + f.readline(), end='')
0: Welcome to this file
1: There is nothing here except
2: This stupid haiku
>>> f.close()
readlines()
>>> import pprint
>>> pprint.pprint(open(r'somefile.txt').readlines())
['Welcome to this file\n',
'There is nothing here except\n',
'This stupid haiku']
write(string)
>>> f = open(r'somefile.txt', 'w')
>>> f.write('this\nis no\nhaiku')
13
>>> f.close()
File will be overwritten!
writelines()
>>> f = open(r'somefile.txt')
>>> lines = f.readlines()
>>> f.close()
>>> lines[1] = "isn't a\n"
>>> f = open(r'somefile.txt', 'w')
>>> f.writelines(lines)
>>> f.close()
One character at a time:
with open('somefile.txt') as f:
while True:
char = f.read(1)
if not char: break
print('Processing:', char)
One line at a time:
with open('somefile.txt') as f:
while True:
line = f.readline()
if not line: break
print(line)
Reading everything:
with open('somefile.txt') as f:
for line in f.readlines():
print(line)
Enother examples of iteration:
with open('somefile.txt') as f:
for line in f:
print(line)
for line in open('somefile.txt'):
print(line)
{ "data": { "sessionMaterial": { "id": "session-material:2019/tieto-ostrava-jaro:files-and-exceptions:0", "title": "Files", "html": "\n \n \n\n <h2>Files</h2>\n<h3>Opening Files</h3>\n<p>You can open files with the open function , which lives in the io module but is automatically imported for you.</p>\n<div class=\"highlight\"><pre><code>>>> f = open('somefile.txt')</code></pre></div><p>You can specify full path to the file and some other optional arguments. In case that you are trying to open file, that doesn't exist, you will receive exception like this:</p>\n<div class=\"highlight\"><pre><code>Traceback (most recent call last):\n File "<stdin>", line 1, in <module>\nFileNotFoundError: [Errno 2] No such file or directory: 'somefile.txt'</code></pre></div><h3>File modes</h3>\n<p>If you use open with only a file name as a parameter, you get a file object you can read from. If you want to write to the file, you must state that explicitly, supplying a mode.</p>\n<table>\n<thead><tr>\n<th>Value</th>\n<th>Description</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>'r'</td>\n<td>Read mode (default)</td>\n</tr>\n<tr>\n<td>'w'</td>\n<td>Write mode</td>\n</tr>\n<tr>\n<td>'x'</td>\n<td>Exclusive write mode</td>\n</tr>\n<tr>\n<td>'a'</td>\n<td>Append mode</td>\n</tr>\n<tr>\n<td>'b'</td>\n<td>Binary mode</td>\n</tr>\n<tr>\n<td>'t'</td>\n<td>Text mode</td>\n</tr>\n<tr>\n<td>'+'</td>\n<td>Read/write mode</td>\n</tr>\n</tbody>\n</table>\n<p>The default mode is 'rt', which means your file is treated as encoded Unicode text.</p>\n<h3>File methods</h3>\n<p><strong>Reading and writing</strong></p>\n<div class=\"highlight\"><pre><code>>>> f = open('somefile.txt', 'w')\n>>> f.write('Hello, ')\n7\n>>> f.write('World!')\n6\n>>> f.close()</code></pre></div><p><strong>Partial reading</strong></p>\n<div class=\"highlight\"><pre><code>>>> f = open('somefile.txt', 'r')\n>>> f.read(4)\n'Hell'\n>>> f.read()\n'o, World!'</code></pre></div><p><strong>Reading from stdin</strong></p>\n<p>somefile.txt file with text:</p>\n<div class=\"highlight\"><pre><code>Welcome to this file\nThere is nothing here except\nThis stupid haiku</code></pre></div><p>somescript.py</p>\n<div class=\"highlight\"><pre><code>import sys\ntext = sys.stdin.read()\nwords = text.split()\nwordcount = len(words)\nprint('Wordcount:', wordcount)</code></pre></div><p>Command:</p>\n<div class=\"highlight\"><pre><code>cat somefile.txt | python somescript.py\nWordcount: 12</code></pre></div><h3>Method seek()</h3>\n<div class=\"highlight\"><pre><code>>>> f = open(r'somefile.txt', 'w')\n>>> f.write('01234567890123456789')\n20\n>>> f.seek(5)\n5\n>>> f.write('Hello, World!')\n13\n>>> f.close()\n>>> f = open(r'somefile.txt')\n>>> f.read()\n'01234Hello, World!89'</code></pre></div><p>The method tell() returns the current file position.</p>\n<div class=\"highlight\"><pre><code>>>> f = open(r'somefile.txt')\n>>> f.read(3)\n'012'\n>>> f.read(2)\n'34'\n>>> f.tell()\n5</code></pre></div><h3>Closing files</h3>\n<p>You should always close files before you exit the script.</p>\n<ul>\n<li>Might help to avoid keeping the file uselessly "locked" against modification in some operating systems.</li>\n<li>You should always close a file you have written to because Python may buffer the data you have written and the data might not be written to the file at all.</li>\n</ul>\n<p>You can use try, finally:</p>\n<div class=\"highlight\"><pre><code># Open your file here\ntry:\n # Write data to your file\nfinally:\n file.close()</code></pre></div><h3>With statement</h3>\n<div class=\"highlight\"><pre><code>with open("somefile.txt") as somefile:\n do_something(somefile)</code></pre></div><p>The with statement simplifies exception handling by encapsulating common\npreparation and cleanup tasks.</p>\n<p>In addition, it will automatically close the file. The with statement provides a way for ensuring that a clean-up is always used.</p>\n<p><strong>Without with statement</strong></p>\n<div class=\"highlight\"><pre><code>file = open("welcome.txt")\ndata = file.read()\nprint data\nfile.close() # It's important to close the file when you're done with it</code></pre></div><p><strong>With with statement</strong></p>\n<div class=\"highlight\"><pre><code>with open("welcome.txt") as file: # Use file to refer to the file object\n data = file.read()\n do something with data</code></pre></div><h3>Another file methods</h3>\n<p>Let's use our somefile.txt.</p>\n<p><strong>read(n)</strong></p>\n<div class=\"highlight\"><pre><code>>>> f = open(r'somefile.txt')\n>>> f.read(7)\n'Welcome'\n>>> f.read(4)\n' to '\n>>> f.close()</code></pre></div><p><strong>read()</strong></p>\n<div class=\"highlight\"><pre><code>>>> f = open(r'somefile.txt')\n>>> print(f.read())\nWelcome to this file\nThere is nothing here except\nThis stupid haiku\n>>> f.close()</code></pre></div><p><strong>readline()</strong></p>\n<div class=\"highlight\"><pre><code>>>> f = open(r'somefile.txt')\n>>> for i in range(3):\n print(str(i) + ': ' + f.readline(), end='')\n0: Welcome to this file\n1: There is nothing here except\n2: This stupid haiku\n>>> f.close()</code></pre></div><p><strong>readlines()</strong></p>\n<div class=\"highlight\"><pre><code>>>> import pprint\n>>> pprint.pprint(open(r'somefile.txt').readlines())\n['Welcome to this file\\n',\n'There is nothing here except\\n',\n'This stupid haiku']</code></pre></div><p><strong>write(string)</strong></p>\n<div class=\"highlight\"><pre><code>>>> f = open(r'somefile.txt', 'w')\n>>> f.write('this\\nis no\\nhaiku')\n13\n>>> f.close()</code></pre></div><div class=\"admonition warn\"><p class=\"admonition-title\">File will be overwritten!</p>\n</div><p><strong>writelines()</strong></p>\n<div class=\"highlight\"><pre><code>>>> f = open(r'somefile.txt')\n>>> lines = f.readlines()\n>>> f.close()\n>>> lines[1] = "isn't a\\n"\n>>> f = open(r'somefile.txt', 'w')\n>>> f.writelines(lines)\n>>> f.close()</code></pre></div><h3>Iterations</h3>\n<p>One character at a time:</p>\n<div class=\"highlight\"><pre><code>with open('somefile.txt') as f:\n while True:\n char = f.read(1)\n if not char: break\n print('Processing:', char)</code></pre></div><p>One line at a time:</p>\n<div class=\"highlight\"><pre><code>with open('somefile.txt') as f:\n while True:\n line = f.readline()\n if not line: break\n print(line)</code></pre></div><p>Reading everything:</p>\n<div class=\"highlight\"><pre><code>with open('somefile.txt') as f:\n for line in f.readlines():\n print(line)</code></pre></div><p>Enother examples of iteration:</p>\n<div class=\"highlight\"><pre><code>with open('somefile.txt') as f:\n for line in f:\n print(line)</code></pre></div><div class=\"highlight\"><pre><code>for line in open('somefile.txt'):\n print(line)</code></pre></div>\n\n\n " } } }