PYTHON READ AND WRITING FILES
Python provides several ways to read and write files. Here’s a brief summary with examples:
Reading Files
open()
function: The most basic way to read a file is using the built-inopen()
function. The syntax is:
f = open("file.txt", "r")
content = f.read()
f.close()
2. with
statement: A more pythonic way to read a file is using the with
statement, which automatically closes the file for you. The syntax is:
with open("file.txt", "r") as f:
content = f.read()
3. readline()
method: To read a file line by line, you can use the readline()
method. The syntax is:
with open("file.txt", "r") as f:
line = f.readline()
while line:
# process the line
line = f.readline()
4. for
loop: Another way to read a file line by line is using a for
loop. The syntax is:
with open("file.txt", "r") as f:
for line in f:
# process the line
Writing Files
open()
function: To write to a file, you can open it in write mode ("w"
) or append mode ("a"
). The syntax for writing to a file is:
f = open("file.txt", "w")
f.write("Hello, world!")
f.close()
2. with
statement: The with
statement can also be used for writing to a file. The syntax is:
with open("file.txt", "w") as f:
f.write("Hello, world!")
3. write()
method with multiple lines: To write multiple lines to a file, use the write()
method with newline characters (\n
). For example:
with open("file.txt", "w") as f:
f.write("Line 1\n")
f.write("Line 2\n")
f.write("Line 3\n")
4. writelines()
method with a list of strings: To write a list of strings to a file, use the writelines()
method. For example:
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("file.txt", "w") as f:
f.writelines(lines)
These are the basics of reading and writing files in Python.
Follow, Like and share