3. File I/O in Python
open (file_name,access_mode,buffering)
read(byte_count)
write(data)
close()
os.rename()
os.remove()
4. File access modes
r
Opens a file for reading only. The file pointer is placed at
the beginning of the file. This is the default mode.
w
Opens a file for writing only. Overwrites the file if the file
exists. If the file does not exist, creates a new file for
writing.
a
Opens a file for appending. The file pointer is at the end of
the file if the file exists. That is, the file is in the
append mode. If the file does not exist, it creates a new file
for writing.
Full list :
http://www.tutorialspoint.com/python/python_files_io.htm
5. Creating File
>>> file = open('pysec.txt', 'w')
>>> file
<open file 'pysec.txt', mode 'w' at 0x7f3e7c8dc4b0>
>>> for count in range(0,100):
... file.write(str(count) + 'n')
...
>>> file.close()
>>>
9. read file
>>> file = open('pysec.txt','r')
>>> for line in file.readlines():
... print line.strip()
...
0
1
2
3
4
.
.
196
197
198
199
10. rename file and remove file
>>> import os
>>> os.rename('pysec.txt', 'pysec101.txt')
>>>
$
$ ls
code pysec101.txt pres_file handling.txt
os.remove(file_name)
>>> import os
>>>os.remove('pysec101.txt')
$
$ ls
code pres_file handling.txt
11. This work is licensed under the Creative Commons
Attribution-NoDerivs 3.0 Unported License.
To view a copy of this license, visit http://creativecommons.org/licenses/by-nd/3.0/
Copyright 2013 Mohammad reza Kamalifard.
All rights reserved.