Tutorialslot.com

youtube facebook twitter gmail pinterest

File Handling in python


Python helps in manipulating various kinds of files which includes video files,music files,textual file.Text files and binary files are the major types of files. Text files provides files as a simple text whereas the binary files includes binary data which can be read only by computer.

Syntax:
file var = open(file_name,[access_mode],[buffering])

access_mode: The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc.
buffering: If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file.

r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.
r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file.

File write:
It is used to write or add any string to an open file. It is represented by "write()" method.

Syntax:
fileObject.write(string);

Example:
file = open("file.txt", "w")
file.write( "Tutorialslot is a great Education Website.\nYeah its great!!\n")
file.close()

Output:
file.txt:
Tutorialslot is a great Education Website.
Yeah its great!!

File read:
It is used to read the contents of an open file. It is represented by "read()" method.

Syntax:
fileObject.read([count]);
If count is missing then it reads the contents as much as possible in a open file.

Example:
file = open("file.txt", "r+")
str = file.read(10)
print ("File Contains : ", str)
file.close()

Output:
file.txt
File Contains :Tutorialslot is a great Education Website.
Yeah its great!!



Advertisement Powered By Google Adsense






IF YOU LIKE THIS TUTORIALS PLEASE SHARE

Share on whatsapp

POPULAR TAGS

python python tutorial learn python learning python python code learning java python language python documentation python tutor python basics python download python online python for dummies how to learn python