File Operation in Python
File
operation is an important part of python programming which enables to work with
external file. Most of the operation related in input/output and file
manipulation we perform using predefined/built in function. Primarily we can
say it’s similar to C programming with reading/writing modes and operation:
Code
Snippet
languages
= ["C", "C++", "Perl", "Python"]
fdemo
= open("aadicsDemo.txt","w")
for
x in languages:
fdemo.write("This is " +x
+"\r\n")
fdemo.close()
fdemo
= open("aadicsDemo.txt","a+")
for
x in languages:
fdemo.write("This is Appended " +x +"\r\n")
fdemo.close()
Syntax
open(filelocation,
readingmode)
Reading Mode
"r" Open file for reading. The stream
is positioned at the beginning
of
the file.
"r+" Open for reading and writing. The stream is positioned at
the
beginning of the file.
"w" Truncate file to zero length or
create text file for writing.
The
stream is positioned at the beginning of the file.
"w+" Open for reading and writing. The file is created if it does
not exist, otherwise it is truncated. The stream
is positioned
at the beginning of the file.
"a" Open
for writing. The file is created if it
does not exist.
The
stream is positioned at the end of the file.
"a+" Open for reading and writing. The file is created if it does
not exist.
The stream is positioned at the end of the file.
File Manipulation functions
x
= json.load(f) Loading data into x from file f
json.dump(x,
f) x is
data object , f is file object
output
= open('aadicsDemo.txt', 'w') Create
output file ('w' means write).
input
= open('data', 'r') Create input file ('r' means read).
readInput=
input.read( ) Read entire file
into a single string.
readInput=
input.read(N) Read N bytes
(1 or more).
readInput=
input.readline( ) Read next
line (through end-line marker).
readLine=input.readlines(
) Read entire file into
list of line strings.
output.write(str) Write string str into file.
output.writelines(ln) Write all line
strings in list ln into file.
output.close(
) Manual
close (done for you when file collected).
File Operation in Python
Reviewed by Rupesh
on
23:46
Rating:
No comments: