Unit 4
Unit 4
Example –
with open("example.txt", "r") as file:
content = file.read()
print(content) # Prints entire content of the file
readline()-
The readline() function reads the next line from the file.
Each call to readline() reads one line from the file.
After reading, the file pointer is moved to the beginning of
the next line.
It reads until it encounters a newline character (\n), which
signifies the end of a line.
If the file is already at the end, it returns an empty string.
Returns a string containing a single line from the file.
Example –
with open("example.txt", "r") as file:
line = file.readline()
print(line) # Prints one line from the file
Readlines() –
The readlines() function reads all lines from the file and
returns them as a list of strings.
It reads the entire content of the file, splitting it into lines.
Each line is returned as a string within a list.
The newline characters (\n) at the end of each line are
included in the string.
Returns a list of strings, where each string represents one
line of the file.
Write() -
• The write() function is used to write a string to a file.
• It writes the content of the string passed as an argument to the
file.
• It does not append a newline (\n) at the end of the string; you
must explicitly include a newline if needed.
• The file pointer is moved to the end of the string after writing.
Example-
with open("example.txt", "w") as file:
file.write("This is a line in the file.\n")
file.write("This is another line.")
writelines() –
The writelines() function is used to write a list of strings to a file.
It takes an iterable (like a list or tuple) containing strings and
writes each string to the file.
Returns None (it does not return any value, but writes the strings
to the file).
Example –
lines = ["This is the first line.\n", "This is the second line.\n",
"This is the third line.\n"]
with open("example.txt", "w") as file:
file.writelines(lines)