ALevel 1 Python 14may
ALevel 1 Python 14may
O Level / A Level
Filenames
Every disk file has a name, and one must use filenames when dealing with disk files.
Filenames are stored as strings, just like other text data.
The rules as to what is acceptable for filenames and what is not, differ from one operating
system to another.
Opening a File
The process of creating a stream linked to a disk file is called opening the file.
When one opens a file, it becomes available for
o reading (meaning that data is input from the file to the program),
o writing (meaning that data from the program is saved in the file), or
o both.
After working with the file, close the file.
Syntax File_Pointer.close( )
Example
fp=open("test.txt", 'w')
fp.close( )
Writing a File
Writing a string or sequence of bytes (for binary files) is done using the write( ) method.
To write into a file in Python, it is need to open it in write(w), append(a) or exclusive
creation(x) mode.
The write(w) mode, overwrite into the file if it already exists.
Example
fp=open("test.txt", 'w')
fp.write("My File1\n")
fp.write("Line2\n")
fp.write("Line3")
fp.close( )
Reading a File
To read the content from the file use the read(size) method to read data.
If the size parameter is not specified, it reads and returns up to the end of the file.
To read from a file in Python, it is need to open it with read(r) mode.
Syntax File_Pointer.read(size)
Example
fp=open("test.txt", 'r')
#Read the first 4 character
x=fp.read(4)
print(x)
ile
1
Line2
Line3
Syntax File_Pointer.readline( )
Example
fp=open("test.txt", 'r')
Output
My File1
Line2
Line3
Reading a complete File line by line
We can read a file linebyline using a for loop
Line2
Line3