UNIT-4 NOTES python programming
UNIT-4 NOTES python programming
Example:
Opening a file creates a file object. In this example, the
variable f refers to the new file object.
>>> f = open("test.dat","w")
>>> print f
The open function takes two arguments. The first is the name of
the file, and the second is the mode. Mode "w" means that we are
opening the file for writing.
output_file.close()
● When opening a file for writing, there is not much
chance of an I/O error occurring.
● The provided file name does not need to exist since it is
being created (or overwritten).
● Thus, the only error that may occur is if the file system
(such as the hard disk) is full.
readline( ):
● We can also use the f.readline( ) function to read one
full line at a time.
● The readline method returns as a string the next line of
a text file, including the end-of-line character, \n.
● When the end-of-file is reached, it returns an empty
string as demonstrated in the while loop:
input_file = open('myfile.txt','r')
empty_str = ‘ ‘
line = input_file.readline( )
while line != empty_str :
print((line)
line = input_file.readline( )
input.close( )
line = f.readlines( )
print("Read Line: ", line)
f.close() # Close opened file
Output:
Name of the file: f.txt
Read Line: ['This is 1st line\n', 'This is 2nd line\n', 'This is 3rd line\n', 'This is
4th line\n', 'This is 5th line']
NOTE: Using a for statement, all lines of the file will be read one
by one. Using a while loop, however, lines can be read until a
given value is found.
writelines() function:
● This function writes the content of a list to a file.
Syntax:
# write all the strings present in the list "list_of_lines"
# referenced by file object.
file_name.writelines(list_of_lines)
● As per the syntax, the list of strings that is passed to the writelines()
function is written into the opened file.
● Similar to the write() function, the writelines() function does not add a
newline character(\n) to the end of the string.
Example:
file1 = open("Employees.txt", "w")
lst = []
for i in range(3):
name = input("Enter the name of the employee: ")
lst.append(name + '\n')
file1.writelines(lst)
file1.close()
print("Data is written into the file.")